NameValueCollection to URL Query?

前端 未结 12 2063
温柔的废话
温柔的废话 2020-11-28 05:36

I know i can do this

var nv = HttpUtility.ParseQueryString(req.RawUrl);

But is there a way to convert this back to a url?

v         


        
12条回答
  •  暖寄归人
    2020-11-28 06:28

    The short answer is to use .ToString() on the NameValueCollection and combine it with the original url.

    However, I'd like to point out a few things:

    You cant use HttpUtility.ParseQueryString on Request.RawUrl. The ParseQueryString() method is looking for a value like this: ?var=value&var2=value2.

    If you want to get a NameValueCollection of the QueryString parameters just use Request.QueryString().

    var nv = Request.QueryString;
    

    To rebuild the URL just use nv.ToString().

    string url = String.Format("{0}?{1}", Request.Path, nv.ToString());
    

    If you are trying to parse a url string instead of using the Request object use Uri and the HttpUtility.ParseQueryString method.

    Uri uri = new Uri("");
    var nv = HttpUtility.ParseQueryString(uri.Query);
    string url = String.Format("{0}?{1}", uri.AbsolutePath, nv.ToString());
    

提交回复
热议问题