Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass special characters so ASP.NET MVC can handle correctly query string data?

Tags:

asp.net-mvc

I am using a route like this one:

routes.MapRoute("Invoice-New-NewCustomer",
    "Invoice/New/Customer/New/{*name}",
    new { controller = "Customer", action = "NewInvoice" },
    new { name = @"[^\.]*" });

There is an action which handles this route:

public ActionResult NewInvoice(string name)
{
    AddClientSideValidation();
    CustomerViewData viewData = GetNewViewData();
    viewData.InvoiceId = "0";
    viewData.Customer.Name = name;
    return View("New", viewData);
}

When I call return RedirectToAction("NewInvoice", "Customer", new {name}); and name is equal to "The C# Guy", the "name" parameter is truncated to "The C".

So my question is : What is the best way to handle this kind of special character with ASP.NET MVC?

Thanks!

like image 740
labilbe Avatar asked Dec 17 '08 03:12

labilbe


People also ask

How do you handle special characters in MVC?

I think the url http://.../home/index?id=a%2fb will work. To generate this url you need to change your route: routes. MapRoute( name: "Default", url: "{controller}/{action}", defaults: new { controller = "Home", action = "Index" } );

How do you pass special characters in HTTP request?

If this is the case and you want to send special characters such as +, /, or = in your HTTP request, your data string must be URL-encoded if you send the data using the PostData or QueryString input elements. If you send the data using the parameters specified on the Configuration tab, encoding is done automatically.


2 Answers

Ok, I confirmed that this is now a known issue in ASP.NET Routing, unfortunately. The problem is that deep in the bowels of routing, we use Uri.EscapeString when escaping routing parameters for the Uri. However, that method does not escape the "#" character.

Note that the # character (aka Octothorpe) is technically the wrong character. C♯ the language is actually a "C" followed by a Sharp sign as in music: http://en.wikipedia.org/wiki/Sharp_(music)

If you used the sharp sign, that could potentially solve this problem. :P

Another solution, since most people will want to use the octothorpe is to write a custom route for this route and after getting the virtual path path, encode the # sign using HttpUtility.UrlEncode which encodes # to %23.

As a follow-up, I wanted to point you to this blog post which talks about passing in other "invalid" characters. http://haacked.com/archive/2010/04/29/allowing-reserved-filenames-in-URLs.aspx

like image 162
Haacked Avatar answered Oct 19 '22 04:10

Haacked


URL Encoding! Change the link so that it encodes special characters.

Server.URLencode(strURL)

C# will become "c%23".

like image 34
EndangeredMassa Avatar answered Oct 19 '22 05:10

EndangeredMassa