0

In my ASP.NET Web API project, I have the following routing defined in Global.asax:

routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "{controller}/{action}"
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}"
            );

I have a controller called UserFeedController with an action with the following signature:

public UserFeedResponseViewModel GetUserFeed(int id)

When I enter the url http://api.mydomain.com/UserFeed/GetUserFeed/4 I get a 404. Why doesn't the second routing rule apply?

MVC routing is quite beyond my power to comprehend.

1 Answer 1

2

Your two routes are basically the same. MVC finds the first route that matches and since you have specified a controller and an action, it thinks you are good to go. It will ignore the id that you specified (I believe it might try to pass it in as a parameter).

I would suggest changing your first route to include API/ at the beginning like so:

routes.MapHttpRoute( 
            name: "DefaultApi", 
            routeTemplate: "API/{controller}/{action}" 
        ); 

        routes.MapHttpRoute( 
            name: "Default", 
            url: "{controller}/{action}/{id}" 
        ); 

That will insure that your routes work properly.

Sign up to request clarification or add additional context in comments.

1 Comment

My God! I didn't notice until now that the code calls two separate methods: MapRoute() and MapHttpRoute(). Why on earth is routing done differently for Web API controllers?! I have changed the code to always use MapHttpRoute() and now I'm getting behaviour I expect...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.