Funny MVC Routing Quirk
I recently ran into a funny quirk with ASP.NET MVC’s routing. I have a method to retrieve attachments which have been uploaded for orders in an ordering system. Originally, I had the method and the route defined like this:
Method signature:
public ActionResult AttachmentView(int orderId, string filename)
Route definition:
routes.MapRoute(name: "Orders_AttachmentView",
url: "Orders/AttachmentView/{ orderId}/{filename}",
defaults: new { controller = "Orders", action = "AttachmentView" }
);
When I tried to call this method, I’d get an error from IIS saying that the resource wasn’t found. I checked and double-checked the route: no problems, everything was correct. I put a breakpoint in the method to ensure that the code wasn’t being reached, and it wasn’t.
Then I thought that maybe the extension on the filename parameter was throwing the route off. I changed the method signature and route definition to reverse the two parameters so that the filename wouldn’t be the last parameter:
Method signature:
public ActionResult AttachmentView(string filename, int orderId)
Route definition:
routes.MapRoute(name: "Orders_AttachmentView",
url: "Orders/AttachmentView/{f ilename}/{orderId}",
defaults: new { controller = "Orders", action = "AttachmentView" }
);
And that did the trick. I guess having that URL end with something like “.gif” was throwing the routing off, which makes sense in hindsight.
Comments
Post a Comment