How to Decode a Url Parameter Using C#

How do I decode a URL parameter using C#?


string decodedUrl = Uri.UnescapeDataString(url)

or

string decodedUrl = HttpUtility.UrlDecode(url)

Url is not fully decoded with one call. To fully decode you can call one of this methods in a loop:

private static string DecodeUrlString(string url) {
string newUrl;
while ((newUrl = Uri.UnescapeDataString(url)) != url)
url = newUrl;
return newUrl;
}

How to get a parameter from a URL encoded?

The encoding is happening in your first line already:

string queryString = new Uri(URL).Query;

Presumably you want to avoid writing your own code to extract the Query part from a URL. Which is sensible. You can still rely on the Uri class to do the parsing for you:

var uri=new Uri(URL);
var queryString= URL.Replace(uri.GetLeftPart(UriPartial.Path), "").TrimStart('?');

———————————————————————————————————

(

var URL="http://a/b/?d= @£$%% sdf we  456 7 5?367";
var uri=new Uri(URL);
Console.WriteLine(uri.Query); // Already url-encoded by the Uri constructor
var queryString = URL.Replace(uri.GetLeftPart(UriPartial.Path), "").TrimStart('?');
Console.WriteLine(System.Web.HttpUtility.ParseQueryString(queryString)); //Not encoded!

)

(As an aside, LinqPad helps)

Asp.Net Core [FromRoute] auto url decode

One way to achieve whatever you're trying to do is to create a custom Attribute. Within the attribute you can essentially intercept the incoming parameter and perform whatever you need.

Attribute Definition:

public class DecodeQueryParamAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext context)
{
string param = context.ActionArguments["param"] as string;
context.ActionArguments["param"] = "Blah"; // this is where your logic is going to sit
base.OnActionExecuting(context);
}
}

And within the controller, you'll need to decorate the action method with the attribute as done below. Route can be modified according to your need.

[HttpGet("/{param}")]
[Attributes.DecodeQueryParamAttribute]
public void Process([FromRoute] string param)
{
// value of param here is 'Blah'
// Action method
}

As a word of caution, when you are going to have encoded strings being passed as query string parameters, you may want to check about allowing Double Escaping and its implications.

C# Web Api action method automatically decoding query parameter

To solve the proble just get rid of the HttpUtility.UrlDecode(encodedString) part.

The value that is coming to the action has been already decoded and you don't need to decode it second time.

In your example:

encodeURIComponent("djdh67-y&+dsdj")        -> djdh67-y%26%2Bdsdj // sent
HttpUtility.UrlDecode("djdh67-y%26%2Bdsdj") -> djdh67-y&+dsdj // done
HttpUtility.UrlDecode("djdh67-y&+dsdj") -> djdh67-y& dsdj // wrong

Not encoded values in GET can be incorrectly interpret by the browser. e.g. symbol & in the request string means next parameter. That's why MVC "thinks" that every get parameter is encoded and decodes it.

In case when string is required in non-changed state it should be passed in the body of a POST request.

How to Encode & Decode Url Containing Special Characters in QueryString?

The First Mistake, I did was the encoding of the end URL instead of the query string parameter.

Encoding:

string myString = "Name=" + HttpUtility.HtmlEncode(name.ToString()) + "&SiteId=" + HttpUtility.HtmlEncode(Id.ToString());
string Final_Url=HttpUtility.UrlEncode(myString);

Decoding:

QName = HttpUtility.ParseQueryString(HttpUtility.UrlDecode(Request.RawUrl.ToString()).Split(new Char[] { '?' })[1])["Name"];
QSiteId= HttpUtility.ParseQueryString(HttpUtility.UrlDecode(Request.RawUrl.ToString()).Split(new Char[] { '?' })[1])["SiteId"];

Credit to @PanagiotisKanavos for giving me the right direction.

WebAPI get request parameters being UrlDecoded at the controller

That is by design. The API framework will decode the URL encoded parameters by default. the encoding should only be used for transporting the data. once on server developer shouldn't have to deal with having to decode it (cross cutting concern). Use the value as intended.

Decoding Url Parameter Values in ASP.NET MVC App

Razor views encode server-side strings by default. To turn off Html encoding, the framework provides the Html.Raw helper.

http://msdn.microsoft.com/en-us/library/gg480740%28v=vs.118%29.aspx

var s = "@Html.Raw(Request.QueryString["s"])";

or wrap with single quote and escape single quote characters:

var s = '@Html.Raw((Request.QueryString["s"] ?? String.Empty).Replace("'","\\'"))';

Be aware that this code is vulnerable to script injection.

URL Encode and Decode in ASP.NET Core


  • For ASP.NET Core 2.0+ just add System.Net namespace - WebUtility class is shipped as part of System.Runtime.Extensions nuget package, that is referenced by default in ASP.NET Core project.

  • For the previous version add Microsoft.AspNetCore.WebUtilities nuget package.

Then the WebUtility class will be available for you:

public static class WebUtility
{
public static string UrlDecode(string encodedValue);
public static string UrlEncode(string value);
}


Related Topics



Leave a reply



Submit