开发者

.NET: Preserving some, but not all query params during redirect

Could someone tell me if the code below would achieve what I want, which is: Check if the query parameters 'return_path' and/or 'user_state' are present in the query string, and if so append them to the query string of the redirect URI.

As I'm not a .NET dev and don't have a server to test this on, I was hoping someone could give me some feedback.

ArrayList vars = new ArrayList();
vars.Add("return_path");
vars.Add("user_state");

string newUrl = "/new/request/uri" + "?";
ArrayList params = new ArrayList();
foreach ( string key in Request.Query开发者_如何学CString ) {
    if (vars.contains(key)) {
        params.Add(key + "=" + HttpUtility.URLPathEncode(Request.QueryString[key]));
    }
}
String[] paramArr = (String[]) params.ToArray( typeof (string) );
String queryString = String.join("&", paramArr);

Response.Redirect(newUrl);

Thank you :)


Looks like it will achieve what you want. My only concern is the use of the raw underscore (_) in a URL. Not sure that's allowed for URL encoding. If it turns out to be an issue, use either hyphen/minus or URL encode the underscore character.

Added after first response:

Ok. Checked. The underscore is bad for host names, not URL params.

Here is the code revamped with generics and LINQ. There's probably more concise syntax out there. Remember the list still only gets iterated once so it should be just as quick.

List<string> varNames = new List<string> { "return_path", "user_state" };

var args = this.Request.QueryString.AllKeys
                .Where( key => varNames.Contains( key) )
                .Select( key => key + "=" + HttpUtility.UrlEncode(Request.QueryString[key]) );

string newUrl = "/new/request/uri";
if (args.Any())
{
    newUrl += "?" + String.Join("&", args);
}

Response.Redirect(newUrl);

Also note:

  • The Html Encode method does not have "Path" in the name,
  • the ? was being added in the original sample regardless of the params found
  • if either of the parameter names appear twice or more then you get a list of values not just one value
  • Response.Redirect is a client redirection so it goes back to the client which is directed to the new URL
  • Response.Redirect throws a ThreadingException to clean up the worker process (which stops any subsequent code from executing and though you can try/catch/finally this special exception type gets rethrown automatically not matter what you do to handle it.
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜