Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 :)

like image 820
Tim Schmelter Avatar asked Apr 07 '11 15:04

Tim Schmelter


People also ask

How do you change a parameter in a URL?

If you have several parameters with the same name, you can append to the regex global flag, like this text. replace(/(src=). *?(&)/g,'$1' + newSrc + '$2'); and that will replaces all the values for those params that shares the same name.

Are URL parameters bad for SEO?

URL parameters can potentially cause a lot of problems when it comes to your SEO. For example, they can create duplicate content, waste crawl budget, and dilute ranking signals.


1 Answers

Here is my implementation:

using System;
using System.Collections.Specialized;
using System.Web; // For this you need to reference System.Web assembly from the GAC

public static class UriExtensions
{
    public static Uri SetQueryVal(this Uri uri, string name, object value)
    {
        NameValueCollection nvc = HttpUtility.ParseQueryString(uri.Query);
        nvc[name] = (value ?? "").ToString();
        return new UriBuilder(uri) {Query = nvc.ToString()}.Uri;
    }
}

and here are some examples:

new Uri("http://host.com/path").SetQueryVal("par", "val")
// http://host.com/path?par=val

new Uri("http://host.com/path?other=val").SetQueryVal("par", "val")
// http://host.com/path?other=val&par=val

new Uri("http://host.com/path?PAR=old").SetQueryVal("par", "new")
// http://host.com/path?PAR=new

new Uri("http://host.com/path").SetQueryVal("par", "/")
// http://host.com/path?par=%2f

new Uri("http://host.com/path")
    .SetQueryVal("p1", "v1")
    .SetQueryVal("p2", "v2")
// http://host.com/path?p1=v1&p2=v2
like image 123
Gian Marco Avatar answered Sep 18 '22 23:09

Gian Marco