简体   繁体   English

从.NET中的一个字符串中获取URL个参数

[英]Get URL parameters from a string in .NET

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.通常,我只会使用Request.Params["theThingIWant"] ,但这个字符串不是来自请求。 I can create a new Uri item like so:我可以像这样创建一个新的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.Query来获取查询字符串......但显然我必须找到一些正则表达式来拆分它。

Am I missing something obvious, or is there no built in way to do this short of creating a regex of some kind, etc?我是否遗漏了一些明显的东西,或者除了创建某种正则表达式等之外没有内置的方法来做到这一点?

Use static ParseQueryString method of System.Web.HttpUtility class that returns NameValueCollection .使用返回NameValueCollectionSystem.Web.HttpUtility class 的 static ParseQueryString方法。

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.aspxhttp://msdn.microsoft.com/en-us/library/ms150046.aspx查看文档

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

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, ie http://test/test.html?empty= becomes a parameter with an empty value.这是为了在一定程度上容忍“格式错误”的查询字符串,即http://test/test.html?empty=成为具有空值的参数。 The caller can verify the parameters if needed.如果需要,调用者可以验证参数。

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

Looks like you should loop over the values of myUri.Query and parse it from there.看起来您应该遍历myUri.Query的值并从那里解析它。

 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.但是,如果不对一堆格式错误的 URL 进行测试,我不会使用此代码。 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 ETC

@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.我有同样的错误,发现原因是参数一实际上是: http://www.example.com?param1而不是param1 ,这是人们所期望的。

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 function 只需要一个有效的查询字符串参数,该参数只包含问号后的字符,如下所示:

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

You can just use the Uri to get the list of the query strings or find a specific parameter.您可以只使用Uri来获取查询字符串列表或查找特定参数。

Uri myUri = new Uri("http://www.example.com?param1=good&param2=bad");
var params = myUri.ParseQueryString();
var specific = myUri.ParseQueryString().Get("spesific");
var paramByIndex = = myUri.ParseQueryString().Get(1);

You can find more from here: https://docs.microsoft.com/en-us/dotnet/api/system.uri?view=net-5.0您可以从这里找到更多信息: https://docs.microsoft.com/en-us/dotnet/api/system.uri?view=net-5.0

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

Or if you don't know the URL (so as to avoid hardcoding, use the AbsoluteUri或者如果您不知道 URL(为了避免硬编码,请使用AbsoluteUri

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;
        }

Use .NET Reflector to view the FillFromString method of System.Web.HttpValueCollection .使用 .NET Reflector 查看System.Web.HttpValueCollectionFillFromString方法。 That gives you the code that ASP.NET is using to fill the Request.QueryString collection.这为您提供了 ASP.NET 用于填充Request.QueryString集合的代码。

Single line LINQ solution:单线LINQ解决方案:

Dictionary<string, string> ParseQueryString(string query)
{
    return query.Replace("?", "").Split('&').ToDictionary(pair => pair.Split('=').First(), pair => pair.Split('=').Last());
}

if you want in get your QueryString on Default page.Default page means your current page url.如果您想在默认页面上获取 QueryString。默认页面表示您的当前页面 url。 you can try this code:你可以试试这段代码:

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

This is actually very simple, and that worked for me:)这实际上非常简单,对我有用:)

        if (id == "DK")
        {
            string longurl = "selectServer.aspx?country=";
            var uriBuilder = new UriBuilder(longurl);
            var query = HttpUtility.ParseQueryString(uriBuilder.Query);
            query["country"] = "DK";

            uriBuilder.Query = query.ToString();
            longurl = uriBuilder.ToString();
        } 

For anyone who wants to loop through all query strings from a string对于任何想要遍历字符串中的所有查询字符串的人

        foreach (var item in new Uri(urlString).Query.TrimStart('?').Split('&'))
        {
            var subStrings = item.Split('=');

            var key = subStrings[0];
            var value = subStrings[1];

            // do something with values
        }

Easiest way how to get value of know the param name:如何获得知道参数名称的值的最简单方法:

using System.Linq;
string loc = "https://localhost:5000/path?desiredparam=that_value&anotherParam=whatever";

var c = loc.Split("desiredparam=").Last().Split("&").First();//that_value

Here is a sample that mentions what dll to include这是一个示例,其中提到了 dll 要包含的内容

var testUrl = "https://www.google.com/?q=foo";

var data = new Uri(testUrl);

// Add a reference to System.Web.dll
var args = System.Web.HttpUtility.ParseQueryString(data.Query);

args.Set("q", "my search term");

var nextUrl = $"{data.Scheme}://{data.Host}{data.LocalPath}?{args.ToString()}";
HttpContext.Current.Request.QueryString.Get("id");

I used it and it run perfectly我用了它,它运行得很好

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM