maxp
maxp

Reputation: 25141

ASP.NET Webforms routing - how to stop trailing slash being routed?

Given the following code, in my ASP.NET webform app;

void foo(RouteCollection routes){
   routes.MapPageRoute(string.Empty, "testroute", "~/hello.aspx", false);
}

The problem is, while http://localhost/testroute routes to hello.aspx, http://localhost/testroute/ also routes to hello.aspx.

Is there anyway to prevent this?

Upvotes: 1

Views: 795

Answers (1)

Andrew Barber
Andrew Barber

Reputation: 40150

The best thing to do here, in my opinion, is simply to make sure your website uses consistent URLs in its <a> tags. Don't worry about extraneous paths into your routing mechanism, but instead concentrate on being sure to use only the desired URL pattern for your links.

For example, make sure your website does not contain any <a> tags with href="/testroute/", and it won't matter that it responds to that.

As I noted in the comments, it's actually standard that a trailing slash at the end of the path portion of a URL has no effect; you can include it, or not. This means two 'different' URLs can load the same page: /page.aspx and /page.aspx/ both load the same thing. But there's also another longstanding tradition here that is similar, with default documents; that is, / and /default.aspx will tend to load the same thing.

The solution in that case is, of course, the same as the solution here: Just be sure that your <a> tags use a consistent, single version of the URLs you want to use.


For the record, you could do something that detects the trailing slash and issues a 301 redirect, but I think it's much easier just to make sure you are consistent with the URLs.

Upvotes: 1

Related Questions