Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
376 views
in Technique[技术] by (71.8m points)

c# - How to replace url-parameter?

given is an URL like http://localhost:1973/Services.aspx?idProject=10&idService=14.

What is the most straightforward way to replace both url-parameter values(for example 10 to 12 and 14 to 7)?

Regex, String.Replace, Substring or LinQ - i'm a little stuck.

Thank you in advance,

Tim


I ended with following, that's working for me because this page has only these two parameter:

string newUrl = url.Replace(url.Substring(url.IndexOf("Services.aspx?") + "Services.aspx?".Length), string.Format("idProject={0}&idService={1}", Services.IdProject, Services.IdService));

But thank you for your suggestions :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

This is what I would do:

public static class UrlExtensions
{
    public static string SetUrlParameter(this string url, string paramName, string value)
    {
        return new Uri(url).SetParameter(paramName, value).ToString();
    }

    public static Uri SetParameter(this Uri url, string paramName, string value)
    {           
        var queryParts = HttpUtility.ParseQueryString(url.Query);
        queryParts[paramName] = value;
        return new Uri(url.AbsoluteUriExcludingQuery() + '?' + queryParts.ToString());
    }

    public static string AbsoluteUriExcludingQuery(this Uri url)
    {
        return url.AbsoluteUri.Split('?').FirstOrDefault() ?? String.Empty;
    }
}

Usage:

string oldUrl = "http://localhost:1973/Services.aspx?idProject=10&idService=14";
string newUrl = oldUrl.SetUrlParameter("idProject", "12").SetUrlParameter("idService", "7");

Or:

Uri oldUrl = new Uri("http://localhost:1973/Services.aspx?idProject=10&idService=14");
Uri newUrl = oldUrl.SetParameter("idProject", "12").SetParameter("idService", "7");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...