从。net中的字符串获取url参数。

时间:2022-08-24 12:51:36

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.

我在。net中有一个字符串,它实际上是一个url。我想要一个简单的方法从一个特定的参数得到值。

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:

通常情况下,我只是使用请求。Params["the thingi want "],但这个字符串不是来自请求。我可以创建一个新的Uri项,如下所示:

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.

我可以使用myUri。查询以获取查询字符串…但显然,我必须找到一些正则表达式来分割它。

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

我是否遗漏了一些明显的东西,或者是没有建立的方法来做这样的事情,比如创建某种regex之类的?

11 个解决方案

#1


378  

Use static ParseQueryString method of System.Web.HttpUtility class that returns NameValueCollection.

使用System.Web的静态并行字符串方法。HttpUtility类,返回NameValueCollection。

Uri myUri = new Uri("http://www.example.com?param1=good&param2=bad");
string param1 = HttpUtility.ParseQueryString(myUri.Query).Get("param1");

Check documentation at http://msdn.microsoft.com/en-us/library/ms150046.aspx

检查文档:http://msdn.microsoft.com/en-us/library/ms150046.aspx

#2


39  

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


22  

Here's another alternative if, for any reason, you can't or don't want to use HttpUtility.ParseQueryString().

如果由于某种原因,您不能或不想使用HttpUtility.ParseQueryString(),那么这里还有另一种替代方法。

This is built to be somewhat tolerant to "malformed" query strings, i.e. http://test/test.html?empty= becomes a parameter with an empty value. The caller can verify the parameters if needed.

这是为了对“格式错误”的查询字符串(例如http://test/test.html?empty=成为一个带空值的参数。如果需要,调用者可以验证参数。

public static class UriHelper
{
    public static Dictionary<string, string> DecodeQueryParameters(this Uri uri)
    {
        if (uri == null)
            throw new ArgumentNullException("uri");

        if (uri.Query.Length == 0)
            return new Dictionary<string, string>();

        return uri.Query.TrimStart('?')
                        .Split(new[] { '&', ';' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(parameter => parameter.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries))
                        .GroupBy(parts => parts[0],
                                 parts => parts.Length > 2 ? string.Join("=", parts, 1, parts.Length - 1) : (parts.Length > 1 ? parts[1] : ""))
                        .ToDictionary(grouping => grouping.Key,
                                      grouping => string.Join(",", grouping));
    }
}

Test

测试

[TestClass]
public class UriHelperTest
{
    [TestMethod]
    public void DecodeQueryParameters()
    {
        DecodeQueryParametersTest("http://test/test.html", new Dictionary<string, string>());
        DecodeQueryParametersTest("http://test/test.html?", new Dictionary<string, string>());
        DecodeQueryParametersTest("http://test/test.html?key=bla/blub.xml", new Dictionary<string, string> { { "key", "bla/blub.xml" } });
        DecodeQueryParametersTest("http://test/test.html?eins=1&zwei=2", new Dictionary<string, string> { { "eins", "1" }, { "zwei", "2" } });
        DecodeQueryParametersTest("http://test/test.html?empty", new Dictionary<string, string> { { "empty", "" } });
        DecodeQueryParametersTest("http://test/test.html?empty=", new Dictionary<string, string> { { "empty", "" } });
        DecodeQueryParametersTest("http://test/test.html?key=1&", new Dictionary<string, string> { { "key", "1" } });
        DecodeQueryParametersTest("http://test/test.html?key=value?&b=c", new Dictionary<string, string> { { "key", "value?" }, { "b", "c" } });
        DecodeQueryParametersTest("http://test/test.html?key=value=what", new Dictionary<string, string> { { "key", "value=what" } });
        DecodeQueryParametersTest("http://www.google.com/search?q=energy+edge&rls=com.microsoft:en-au&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1%22",
            new Dictionary<string, string>
            {
                { "q", "energy+edge" },
                { "rls", "com.microsoft:en-au" },
                { "ie", "UTF-8" },
                { "oe", "UTF-8" },
                { "startIndex", "" },
                { "startPage", "1%22" },
            });
        DecodeQueryParametersTest("http://test/test.html?key=value;key=anotherValue", new Dictionary<string, string> { { "key", "value,anotherValue" } });
    }

    private static void DecodeQueryParametersTest(string uri, Dictionary<string, string> expected)
    {
        Dictionary<string, string> parameters = new Uri(uri).DecodeQueryParameters();
        Assert.AreEqual(expected.Count, parameters.Count, "Wrong parameter count. Uri: {0}", uri);
        foreach (var key in expected.Keys)
        {
            Assert.IsTrue(parameters.ContainsKey(key), "Missing parameter key {0}. Uri: {1}", key, uri);
            Assert.AreEqual(expected[key], parameters[key], "Wrong parameter value for {0}. Uri: {1}", parameters[key], uri);
        }
    }
}

#4


11  

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

看起来您应该对myUri的值进行循环。从那里查询和解析它。

 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:

但是,如果不对一堆格式不正确的url进行测试,我就不会使用这段代码。它可能会在某些/所有这些上失效:

  • hello.html?
  • hello.html吗?
  • hello.html?valuelesskey
  • hello.html ? valuelesskey
  • hello.html?key=value=hi
  • hello.html ?关键=价值=你好
  • hello.html?hi=value?&b=c
  • hello.html ?嗨=价值? b = c
  • etc

#5


10  

@Andrew and @CZFox

@Andrew和@CZFox

I had the same bug and found the cause to be that parameter one is in fact: http://www.example.com?param1 and not param1 which is what one would expect.

我有同样的错误,发现原因是参数1实际上是:http://www.example.com?参数1而不是参数1,这是我们所期望的。

By removing all characters before and including the question mark fixes this problem. So in essence the HttpUtility.ParseQueryString function only requires a valid query string parameter containing only characters after the question mark as in:

通过删除之前的所有字符,包括问号,解决了这个问题。所以本质上是HttpUtility。ParseQueryString函数只需要一个有效的查询字符串参数,该参数只包含问号后面的字符,如:

HttpUtility.ParseQueryString ( "param1=good&param2=bad" )

My workaround:

我的解决方案:

string RawUrl = "http://www.example.com?param1=good&param2=bad";
int index = RawUrl.IndexOf ( "?" );
if ( index > 0 )
    RawUrl = RawUrl.Substring ( index ).Remove ( 0, 1 );

Uri myUri = new Uri( RawUrl, UriKind.RelativeOrAbsolute);
string param1 = HttpUtility.ParseQueryString( myUri.Query ).Get( "param1" );`

#6


2  

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");

#7


2  

Use .NET Reflector to view the FillFromString method of System.Web.HttpValueCollection. That gives you the code that ASP.NET is using to fill the Request.QueryString collection.

使用。net反射器来查看System.Web.HttpValueCollection的FillFromString方法。这就是ASP的代码。NET用于填充请求。变量的集合。

#8


1  

HttpContext.Current.Request.QueryString.Get("id");

#9


1  

Or if you don't know the URL (so as to avoid hardcoding, use the AbsoluteUri

或者,如果您不知道URL(为了避免硬编码,请使用绝对uri)。

Example ...

例子……

        //get the full URL
        Uri myUri = new Uri(Request.Url.AbsoluteUri);
        //get any parameters
        string strStatus = HttpUtility.ParseQueryString(myUri.Query).Get("status");
        string strMsg = HttpUtility.ParseQueryString(myUri.Query).Get("message");
        switch (strStatus.ToUpper())
        {
            case "OK":
                webMessageBox.Show("EMAILS SENT!");
                break;
            case "ER":
                webMessageBox.Show("EMAILS SENT, BUT ... " + strMsg);
                break;
        }

#10


0  

if you want in get your QueryString on Default page .Default page means your current page url . you can try this code :

如果你想让你的查询字符串在默认页面。默认页面意味着你当前的页面url。你可以试试下面的代码:

string paramIl = HttpUtility.ParseQueryString(this.ClientQueryString).Get("city");

#11


-2  

I used it and it run perfectly

我用过它,运行得很好

<%=Request.QueryString["id"] %>

#1


378  

Use static ParseQueryString method of System.Web.HttpUtility class that returns NameValueCollection.

使用System.Web的静态并行字符串方法。HttpUtility类,返回NameValueCollection。

Uri myUri = new Uri("http://www.example.com?param1=good&param2=bad");
string param1 = HttpUtility.ParseQueryString(myUri.Query).Get("param1");

Check documentation at http://msdn.microsoft.com/en-us/library/ms150046.aspx

检查文档:http://msdn.microsoft.com/en-us/library/ms150046.aspx

#2


39  

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


22  

Here's another alternative if, for any reason, you can't or don't want to use HttpUtility.ParseQueryString().

如果由于某种原因,您不能或不想使用HttpUtility.ParseQueryString(),那么这里还有另一种替代方法。

This is built to be somewhat tolerant to "malformed" query strings, i.e. http://test/test.html?empty= becomes a parameter with an empty value. The caller can verify the parameters if needed.

这是为了对“格式错误”的查询字符串(例如http://test/test.html?empty=成为一个带空值的参数。如果需要,调用者可以验证参数。

public static class UriHelper
{
    public static Dictionary<string, string> DecodeQueryParameters(this Uri uri)
    {
        if (uri == null)
            throw new ArgumentNullException("uri");

        if (uri.Query.Length == 0)
            return new Dictionary<string, string>();

        return uri.Query.TrimStart('?')
                        .Split(new[] { '&', ';' }, StringSplitOptions.RemoveEmptyEntries)
                        .Select(parameter => parameter.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries))
                        .GroupBy(parts => parts[0],
                                 parts => parts.Length > 2 ? string.Join("=", parts, 1, parts.Length - 1) : (parts.Length > 1 ? parts[1] : ""))
                        .ToDictionary(grouping => grouping.Key,
                                      grouping => string.Join(",", grouping));
    }
}

Test

测试

[TestClass]
public class UriHelperTest
{
    [TestMethod]
    public void DecodeQueryParameters()
    {
        DecodeQueryParametersTest("http://test/test.html", new Dictionary<string, string>());
        DecodeQueryParametersTest("http://test/test.html?", new Dictionary<string, string>());
        DecodeQueryParametersTest("http://test/test.html?key=bla/blub.xml", new Dictionary<string, string> { { "key", "bla/blub.xml" } });
        DecodeQueryParametersTest("http://test/test.html?eins=1&zwei=2", new Dictionary<string, string> { { "eins", "1" }, { "zwei", "2" } });
        DecodeQueryParametersTest("http://test/test.html?empty", new Dictionary<string, string> { { "empty", "" } });
        DecodeQueryParametersTest("http://test/test.html?empty=", new Dictionary<string, string> { { "empty", "" } });
        DecodeQueryParametersTest("http://test/test.html?key=1&", new Dictionary<string, string> { { "key", "1" } });
        DecodeQueryParametersTest("http://test/test.html?key=value?&b=c", new Dictionary<string, string> { { "key", "value?" }, { "b", "c" } });
        DecodeQueryParametersTest("http://test/test.html?key=value=what", new Dictionary<string, string> { { "key", "value=what" } });
        DecodeQueryParametersTest("http://www.google.com/search?q=energy+edge&rls=com.microsoft:en-au&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1%22",
            new Dictionary<string, string>
            {
                { "q", "energy+edge" },
                { "rls", "com.microsoft:en-au" },
                { "ie", "UTF-8" },
                { "oe", "UTF-8" },
                { "startIndex", "" },
                { "startPage", "1%22" },
            });
        DecodeQueryParametersTest("http://test/test.html?key=value;key=anotherValue", new Dictionary<string, string> { { "key", "value,anotherValue" } });
    }

    private static void DecodeQueryParametersTest(string uri, Dictionary<string, string> expected)
    {
        Dictionary<string, string> parameters = new Uri(uri).DecodeQueryParameters();
        Assert.AreEqual(expected.Count, parameters.Count, "Wrong parameter count. Uri: {0}", uri);
        foreach (var key in expected.Keys)
        {
            Assert.IsTrue(parameters.ContainsKey(key), "Missing parameter key {0}. Uri: {1}", key, uri);
            Assert.AreEqual(expected[key], parameters[key], "Wrong parameter value for {0}. Uri: {1}", parameters[key], uri);
        }
    }
}

#4


11  

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

看起来您应该对myUri的值进行循环。从那里查询和解析它。

 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:

但是,如果不对一堆格式不正确的url进行测试,我就不会使用这段代码。它可能会在某些/所有这些上失效:

  • hello.html?
  • hello.html吗?
  • hello.html?valuelesskey
  • hello.html ? valuelesskey
  • hello.html?key=value=hi
  • hello.html ?关键=价值=你好
  • hello.html?hi=value?&b=c
  • hello.html ?嗨=价值? b = c
  • etc

#5


10  

@Andrew and @CZFox

@Andrew和@CZFox

I had the same bug and found the cause to be that parameter one is in fact: http://www.example.com?param1 and not param1 which is what one would expect.

我有同样的错误,发现原因是参数1实际上是:http://www.example.com?参数1而不是参数1,这是我们所期望的。

By removing all characters before and including the question mark fixes this problem. So in essence the HttpUtility.ParseQueryString function only requires a valid query string parameter containing only characters after the question mark as in:

通过删除之前的所有字符,包括问号,解决了这个问题。所以本质上是HttpUtility。ParseQueryString函数只需要一个有效的查询字符串参数,该参数只包含问号后面的字符,如:

HttpUtility.ParseQueryString ( "param1=good&param2=bad" )

My workaround:

我的解决方案:

string RawUrl = "http://www.example.com?param1=good&param2=bad";
int index = RawUrl.IndexOf ( "?" );
if ( index > 0 )
    RawUrl = RawUrl.Substring ( index ).Remove ( 0, 1 );

Uri myUri = new Uri( RawUrl, UriKind.RelativeOrAbsolute);
string param1 = HttpUtility.ParseQueryString( myUri.Query ).Get( "param1" );`

#6


2  

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");

#7


2  

Use .NET Reflector to view the FillFromString method of System.Web.HttpValueCollection. That gives you the code that ASP.NET is using to fill the Request.QueryString collection.

使用。net反射器来查看System.Web.HttpValueCollection的FillFromString方法。这就是ASP的代码。NET用于填充请求。变量的集合。

#8


1  

HttpContext.Current.Request.QueryString.Get("id");

#9


1  

Or if you don't know the URL (so as to avoid hardcoding, use the AbsoluteUri

或者,如果您不知道URL(为了避免硬编码,请使用绝对uri)。

Example ...

例子……

        //get the full URL
        Uri myUri = new Uri(Request.Url.AbsoluteUri);
        //get any parameters
        string strStatus = HttpUtility.ParseQueryString(myUri.Query).Get("status");
        string strMsg = HttpUtility.ParseQueryString(myUri.Query).Get("message");
        switch (strStatus.ToUpper())
        {
            case "OK":
                webMessageBox.Show("EMAILS SENT!");
                break;
            case "ER":
                webMessageBox.Show("EMAILS SENT, BUT ... " + strMsg);
                break;
        }

#10


0  

if you want in get your QueryString on Default page .Default page means your current page url . you can try this code :

如果你想让你的查询字符串在默认页面。默认页面意味着你当前的页面url。你可以试试下面的代码:

string paramIl = HttpUtility.ParseQueryString(this.ClientQueryString).Get("city");

#11


-2  

I used it and it run perfectly

我用过它,运行得很好

<%=Request.QueryString["id"] %>