C# 替换查询字符串中的项目

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/772253/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-05 00:32:40  来源:igfitidea点击:

Replace item in querystring

c#asp.netquery-string

提问by Karsten

I have a URL that also might have a query string part, the query string might be empty or have multiple items.

我有一个 URL,它也可能有一个查询字符串部分,查询字符串可能为空或有多个项目。

I want to replace one of the items in the query string or add it if the item doesn't already exists.

我想替换查询字符串中的项目之一,或者如果该项目不存在则添加它。

I have an URI object with the complete URL.

我有一个带有完整 URL 的 URI 对象。

My first idea was to use regex and some string magic, that should do it.

我的第一个想法是使用正则表达式和一些字符串魔法,应该可以做到。

But it seems a bit shaky, perhaps the framework has some query string builder class?

不过好像有点不靠谱,也许框架有一些查询字符串构建器类?

采纳答案by knut

Maybe you could use the System.UriBuilderclass. It has a Queryproperty.

也许你可以使用这个System.UriBuilder类。它有一个Query属性。

回答by majkinetor

You can speed up RegExps by precompiling them.

您可以通过预编译来加速 RegExp。

Check out this tutorial

看看这个教程

回答by Cerebrus

No, the framework doesn't have any existing QueryStringBuilder class, but usually the querystring information in a HTTP request is available as an iterable and searchable NameValueCollectionvia the Request.Querystringproperty.

不,该框架没有任何现有的 QueryStringBuilder 类,但通常 HTTP 请求中的查询字符串信息可作为可迭代和可搜索NameValueCollectionRequest.Querystring属性使用。

Since you are starting off with a Uriobject, however, you will need to obtain the querystring portion using the Queryproperty of the Uriobject. This will yield a string of the form:

Uri但是,由于您是从对象开始的,因此您需要使用对象的Query属性获取查询字符串部分Uri。这将产生以下形式的字符串:

Uri myURI = new Uri("http://www.mywebsite.com/page.aspx?Val1=A&Val2=B&Val3=C");
string querystring = myURI.Query;

// Outputs: "?Val1=A&Val2=B&Val3=C". Note the ? prefix!
Console.WriteLine(querystring);

You can then split this string on the ampersand character to differentiate it into different querystring parameters-value pairs. Then again split each parameter on the "=" character to differentiate it into a key and value.

然后,您可以在与号字符上拆分此字符串,以将其区分为不同的查询字符串参数-值对。然后再次拆分“=”字符上的每个参数以将其区分为键和值。

Since your final goal is to search for a particular querystring key and if necessary create it, you should try to (re)create a collection (preferably, a generic one) that allows you easily search in the collection, similar to the facility provided by the NameValueCollectionclass.

由于您的最终目标是搜索特定的查询字符串键并在必要时创建它,您应该尝试(重新)创建一个集合(最好是一个通用的),以便您在集合中轻松搜索,类似于提供的工具在NameValueCollection类。

回答by Igal Tabachnik

I answered a similar questiona while ago. Basically, the best way would be to use the class HttpValueCollection, which the QueryStringproperty actually is, unfortunately it is internal in the .NET framework. You could use Reflector to grab it (and place it into your Utils class). This way you could manipulate the query string like a NameValueCollection, but with all the url encoding/decoding issues taken care for you.

不久前我回答了一个类似的问题。基本上,最好的方法是使用 class HttpValueCollection,它QueryString实际上是属性,不幸的是它在 .NET 框架中是内部的。您可以使用 Reflector 来抓取它(并将其放入您的 Utils 类中)。通过这种方式,您可以像 NameValueCollection 一样操作查询字符串,但所有 url 编码/解码问题都会为您处理。

HttpValueCollectionextends NameValueCollection, and has a constructor that takes an encoded query string (ampersands and question marks included), and it overrides a ToString()method to later rebuild the query string from the underlying collection.

HttpValueCollectionextends NameValueCollection,并有一个构造函数,它接受一个编码的查询字符串(包括与号和问号),它覆盖了一个ToString()方法,以便稍后从基础集合中重建查询字符串。

回答by Steve

I agree with Cerebrus. Sticking to the KISS principle, you have the querystring,

我同意大脑。坚持 KISS 原则,你有查询字符串,

string querystring = myURI.Query; 

you know what you are looking for and what you want to replace it with.

你知道你在寻找什么以及你想用什么来代替它。

So use something like this:-

所以使用这样的东西:-

if (querystring == "") 
  myURI.Query += "?" + replacestring; 
else 
  querystring.replace (searchstring, replacestring); // not too sure of syntax !!

回答by Damian

string link = page.Request.Url.ToString();

if(page.Request.Url.Query == "")
    link  += "?pageIndex=" + pageIndex;
else if (page.Request.QueryString["pageIndex"] != "")
{
    var idx = page.Request.QueryString["pageIndex"];
    link = link.Replace("pageIndex=" + idx, "pageIndex=" + pageIndex);
}
else 
    link += "&pageIndex=" + pageIndex;

This seems to work really well.

这似乎工作得很好。

回答by Marc

I used the following code to append/replace the value of a parameter in the current request URL:

我使用以下代码附加/替换当前请求 URL 中的参数值:

    public static string CurrentUrlWithParam(this UrlHelper helper, string paramName, string paramValue)
    {
        var url = helper.RequestContext.HttpContext.Request.Url;
        var sb = new StringBuilder();

        sb.AppendFormat("{0}://{1}{2}{3}",
                        url.Scheme,
                        url.Host,
                        url.IsDefaultPort ? "" : ":" + url.Port,
                        url.LocalPath);

        var isFirst = true;

        if (!String.IsNullOrWhiteSpace(url.Query))
        {
            var queryStrings = url.Query.Split(new[] { '?', ';' });
            foreach (var queryString in queryStrings)
            {
                if (!String.IsNullOrWhiteSpace(queryString) && !queryString.StartsWith(paramName + "="))
                {
                    sb.AppendFormat("{0}{1}", isFirst ? "?" : ";", queryString);
                    isFirst = false;
                }
            }
        }

        sb.AppendFormat("{0}{1}={2}", isFirst ? "?" : ";", paramName, paramValue);

        return sb.ToString();
    }

Maybe this helps others when finding this topic.

也许这有助于其他人找到这个话题。

Update:

更新:

Just saw the hint about UriBuilder and did a second version using UriBuilder, StringBuilder and Linq:

刚刚看到有关 UriBuilder 的提示,并使用 UriBuilder、StringBuilder 和 Linq 做了第二个版本:

    public static string CurrentUrlWithParam(this UrlHelper helper, string paramName, string paramValue)
    {
        var url = helper.RequestContext.HttpContext.Request.Url;
        var ub = new UriBuilder(url.Scheme, url.Host, url.Port, url.LocalPath);

        // Query string
        var sb = new StringBuilder();
        var isFirst = true;
        if (!String.IsNullOrWhiteSpace(url.Query))
        {
            var queryStrings = url.Query.Split(new[] { '?', ';' });
            foreach (var queryString in queryStrings.Where(queryString => !String.IsNullOrWhiteSpace(queryString) && !queryString.StartsWith(paramName + "=")))
            {
                sb.AppendFormat("{0}{1}", isFirst ? "" : ";", queryString);
                isFirst = false;
            }
        }
        sb.AppendFormat("{0}{1}={2}", isFirst ? "" : ";", paramName, paramValue);
        ub.Query = sb.ToString();

        return ub.ToString();
    }

回答by Dani

I use following method:

我使用以下方法:

    public static string replaceQueryString(System.Web.HttpRequest request, string key, string value)
    {
        System.Collections.Specialized.NameValueCollection t = HttpUtility.ParseQueryString(request.Url.Query);
        t.Set(key, value);
        return t.ToString();
    }

回答by Chris

I found this was a more elegant solution

我发现这是一个更优雅的解决方案

var qs = HttpUtility.ParseQueryString(Request.QueryString.ToString());
qs.Set("item", newItemValue);
Console.WriteLine(qs.ToString());

回答by psulek

Lets have this url: https://localhost/video?param1=value1

让我们有这个网址: https://localhost/video?param1=value1

At first update specific query string param to new value:

首先将特定的查询字符串参数更新为新值:

var uri = new Uri("https://localhost/video?param1=value1");
var qs = HttpUtility.ParseQueryString(uri.Query);
qs.Set("param1", "newValue2");

Next create UriBuilderand update Queryproperty to produce new uri with changed param value.

接下来创建UriBuilder和更新Query属性以生成具有更改参数值的新 uri。

var uriBuilder = new UriBuilder(uri);
uriBuilder.Query = qs.ToString();
var newUri = uriBuilder.Uri;

Now you have in newUrithis value: https://localhost/video?param1=newValue2

现在你有newUri这个值: https://localhost/video?param1=newValue2