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 filenameint orderId)

Route definition:
            routes.MapRoute(name: "Orders_AttachmentView",
                url: "Orders/AttachmentView/{filename}/{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

Popular posts from this blog

How To Mock Out Child Components In Unit Tests of Angular 2 Code

A Generic Method Using HttpClient to Make a Synchronous Get Request

The Cause and Solution for the "System.Runtime.Serialization.InvalidDataContractException: Type 'System.Threading.Tasks.Task`1[YourTypeHere]' cannot be serialized." Exception