Get url parameters from a string in .NET

2018-12-31 16:28发布

I've got a string in .NET which is actually a url. I want an easy way to get the value from a particular parameter.

Normally, I'd just use Request.Params["theThingIWant"], but this string isn't from the request. I can create a new Uri item like so:

Uri myUri = new Uri(TheStringUrlIWantMyValueFrom);

I can use myUri.Query to get the query string...but then I apparently have to find some regexy way of splitting it up.

Am I missing something obvious, or is there no built in way to do this short of creating a regex of some kind, etc?

11条回答
刘海飞了
2楼-- · 2018-12-31 17:18

This is probably what you want

var uri = new Uri("http://domain.test/Default.aspx?var1=true&var2=test&var3=3");
var query = HttpUtility.ParseQueryString(uri.Query);

var var2 = query.Get("var2");
查看更多
爱死公子算了
3楼-- · 2018-12-31 17:19

I used it and it run perfectly

<%=Request.QueryString["id"] %>
查看更多
残风、尘缘若梦
4楼-- · 2018-12-31 17:23

Looks like you should loop over the values of myUri.Query and parse it from there.

 string desiredValue;
 foreach(string item in myUri.Query.Split('&'))
 {
     string[] parts = item.Replace('?', '').Split('=');
     if(parts[0] == "desiredKey")
     {
         desiredValue = parts[1];
         break;
     }
 }

I wouldn't use this code without testing it on a bunch of malformed URLs however. It might break on some/all of these:

  • hello.html?
  • hello.html?valuelesskey
  • hello.html?key=value=hi
  • hello.html?hi=value?&b=c
  • etc
查看更多
梦醉为红颜
5楼-- · 2018-12-31 17:23
HttpContext.Current.Request.QueryString.Get("id");
查看更多
公子世无双
6楼-- · 2018-12-31 17:25

You can use the following workaround for it to work with the first parameter too:

var param1 =
    HttpUtility.ParseQueryString(url.Substring(
        new []{0, url.IndexOf('?')}.Max()
    )).Get("param1");
查看更多
登录 后发表回答