Why is ASP.NET MVC ignoring my trailing slash? - asp.net-mvc

Consider the following route:
routes.MapRoute(
"Service", // Route name
"service/", // URL with parameters
new {controller = "CustomerService", action = "Index"} // Parameter defaults
);
Using Url.Action("Service", "CustomerService") produces an url of /service instead of the expected /service/
Is there any way to get this to work, or do I have to resort to implementing my own routing deriving from RouteBase?

Legenden - there is no immediate solution to the problem. You may have run across Jason Young's blog post about the issue, which is very informative. Scott Hanselmann posted a reply to it here, basically stating that he didn't think it was a big deal, and if it is, you can leverage the new IIS7 rewrite module to solve it.
Ultimately though, you might want to look at a solution that was posted by murad on a similar question on StackOverflow: Trailing slash on an ASP.NET MVC route

In your page load event add:
Dim rawUrl As String = HttpContext.Current.ApplicationInstance.Request.RawUrl
If Not rawUrl.EndsWith("/") Then
HttpContext.Current.ApplicationInstance.Response.RedirectPermanent(String.Format("~{0}/", rawUrl))
End If

Related

WebApi route with urlEncoded part

I have route:
config.Routes.MapHttpRoute(
name: "RestApi",
routeTemplate: "rest/{storage}/{controller}/{id}/{action}",
defaults: new
{
id = RouteParameter.Optional,
action = "Index"
}
{id} parameter can be URI itself, and I encode it. For example, route can be:
/rest/main/nodes/http%3A%2F%2Fwww.company.com%2Fns%2FGeo%23United_States/rdf
But this way wrong, it isn't work. With simple {id} parameter it is OK.
What I should do to make it works?
What I should do to make it works?
Just use query string parameters if you intend to send arbitrary characters to the server:
/rest/main/nodes/rdf?url=http%3A%2F%2Fwww.company.com%2Fns%2FGeo%23United_States
You may read the following blog post from Scott Hanselmann in which he covers the difficulties of using such values in the path portion of the url.
I quote his conclusion:
After ALL this effort to get crazy stuff in the Request Path, it's
worth mentioning that simply keeping the values as a part of the Query
String (remember WAY back at the beginning of this post?) is easier,
cleaner, more flexible, and more secure.

Special Characters in ActionLink. asp mvc

I'm using asp.net mvc 4 to build a web application.
To create url to an action I'm using ActionLink as follows:
#Html.ActionLink("Details", "Details", new { id=item.PrimaryKey })
item.PrimaryKey can be a string, so it can cointains dots or slashes or any other special character; When it contains dots or slashes i get an 404 error. ¿How can I avoid it?
I found a solution here
http://mrpmorris.blogspot.mx/2012/08/asp-mvc-encoding-route-values.html
but its complicated
¿Is there an easier solution to this?
I found a solution here
http://mrpmorris.blogspot.mx/2012/08/asp-mvc-encoding-route-values.html
but its complicated
That's because the problem you are attempting to solve is complicated. You may take a look at the following blog post from Scott Hanselman in which he explains the various challenges in doing this. I will summarize his conclusion:
After ALL this effort to get crazy stuff in the Request Path, it's
worth mentioning that simply keeping the values as a part of the Query
String (remember WAY back at the beginning of this post?) is easier,
cleaner, more flexible, and more secure.
So basically if your ids can contain any characters, they should be passed as query string parameters and not part of the Uri path.
But if you insist and want to have the ids as part of the Uri path you may be inspired by how StackOverflow does it. Look at the address bar of your browser now. You will see this:
https://stackoverflow.com/questions/15697189/special-characters-in-actionlink-asp-mvc
Notice how the url contains 2 tokens: the actual id and a SEO friendly name. Jeff Atwood showed a sample filter function they are using to generate those SEO friendly slugs. The slug is just for SEO purposes. You could replace it with whatever you want and get the same result:
https://stackoverflow.com/questions/15697189/foo-bar
You can use Server.UrlEncode() to encode it:
#Html.ActionLink("Details", "Details", new { id=Server.UrlEncode(item.PrimaryKey) })
reference to msdn with example

How do ASP.NET MVC Routes work?

I have the following route's defined:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = "" }
);
// Added custom route here!
routes.MapRoute(
"CatchAll",
"{*catchall},"
new { controller = "Error", action = "NotFound" }
);
}
nothing new - that's the default ASP.NET MVC1 RegisterRoutes method, with one custom route added.
Now, if I goto the following url, i get a 404...
http://whatever/Home/MissingActionMethod
So there's no ActionMethod called MissingActionMethod in the HomeController. So, does this mean, if i goto the 1st route defined, above .. and fail to find an action .. do I then come back and try the second route? rinse-repeat?
Or once i match a route, i then try and execute that route .. and if i fail (ie, find the action is missing) .. then .. bad luck? boomski?
cheers!
EDIT/UPDATE:
Thanks heaps for the replies, but they are not reading my question properly :( I know
1) order of routes are important
b) haack's route debugger
but my question is not about that. I'm asking that .. if the first route is 'handled' .. but fails .. does it then go down the list to the next one?
So, in my example above. The first route called 'Default' is matched against the url/resource requested ... but when the framework tries to find an action, which is missing .. it 404's.
So .. does that mean the framework first matches the "default" route .. tries it .. fails .. goes BACK to the route list .. tries to find the next route that matches .. and finally fails so it then gives up?
Or it only finds the first and only the first route it matches .. and if it fails to find the controller and/or action .. then it just gives up there and then? (This is what i suspect). And if so .. how does it then figure out how to 404?
Update #2:
Phil Haack actually talks about my question, a bit ... but doesn't answer the part I was curious about -> how and where it determines a 404 resource not found.
Routes != Actions.
It goes like this - on incoming request, routing module searches for first route in route table that matches and then tries to call appropriate action.
If action is not found, request fails and returns 404 (it does NOT try to look for next route).
But it should be possible to extend framework in order to achieve this. My first guess - You could write your own RouteHandler.
RouteHandler
Not really specific to ASP.NET MVC, the RouteHandler is the component that decide what to do after the route has been selected. Obviously if you change the RouteHandler you end up handling the request without ASP.NET MVC, but this can be useful if you want to handle a route directly with some specific HttpHanlders or even with a classic WebForm.
Anyway - I wouldn't recommend it though. It's better to keep routing dumb.
After some quick googling - I'm not so optimistic about this anymore. :)
I don't think it will check the second route, because the first one specified is the default. I think if you switch them, it would check CatchAll, see that it doesn't match the route specified in the URL, and then fall back to the default, since you're only providing a controller name, not a route. I think if you wanted CatchAll to do anything at all, you'd have to hit http://whatever/CatchAll/Error/MissingActionMethod, and it would have to come before the default.
See this for more in-depth information.
You should try using the Phil Haack's route debugger from http://haacked.com/archive/2008/03/13/url-routing-debugger.aspx, to see what route is matching and why.

IIS routing configuration error with ASP.NET MVC?

I am unsure if my title was accurate enough. I am trying to make SEO URLs for my website which is developed in ASP.NET MVC. I configured my route to include:
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}/{seo}", // URL with parameters, SEO will up completely optional and used for strings to provide Search Engine Optimization.
new { controller = "Home", action = "Index", id = "", seo ="" } // Parameter defaults
);
On my development machine, a link like:
http://localhost:1048/Home/Post/96/Firefighting+ATV+Concept+Twin+Water+Cannons+Gull
works fine, but once I published to the server (Windows 2008 R2 IIS), it doesn't work. For example, the link:
http://www.otakuwire.net/Home/Post/96/Firefighting+ATV+Concept+Twin+Water+Cannons+Gull
gives me a 404.
Is this a routing issue, or some other issue?
This is an IIS issue, not routing. IIS7 is strict in how it deals with the plus symbol + in URLs. The easy fix is to use the dash - instead like everyone else, or be bold and use the space character (which, personal note, looks horrible in the IE address bar).
On ServerFault they present a configuration-based solution to allow + symbols:
https://serverfault.com/questions/76013/iis6-vs-iis7-and-iis7-5-handling-urls-with-plus-sign-in-base-not-querystri

How should I implement localization with ASP.NET MVC routes?

I'm trying to plan for future (months away) localization of a new ASP.NET MVC site.
Trying to decide what makes most sense to do, as far as constructing the URLs and routing.
For instance should I start off immediately with this :
http://www.example.com/en/Products/1001
http://www.example.com/es/Products/1001
or just
http://www.example.com/Products/1001
and then add other languages later
http://www.example.com/en/Products/1001
Thats my basic main issue right now, trying to get the routing correct. I want my URLs to be indexable by a search engine correctly. I'm not even sure if I want language in the URL but I dont think there is a good alternative that wouldn't confuse a search engine.
It leads to all kinds of other questions like 'shouldnt I localize the word products' but for right now I just want to get the routing in place before I launch the english site.
I have exactly the same URL_mapping like you. My route also uses a constraint.
Works for me.
routes.MapRoute(
// Route name
"LocalizedController",
// URL with parameters
"{language}/{controller}/{action}",
// Parameter defaults
new {
controller = "Home", action = "Index",
language = "de"
},
//Parameter constraints
new { language = #"de|en" }
I would use a different URL scheme like so :
en.mysite.com (English)
mysite.com (default language)
ro.mysite.com (Romanian)
etc.
Then I would create a custom route like in this answer.

Resources