A day with .Net

My day to day experince in .net

Web API inside an MVC Area

Posted by vivekcek on May 7, 2016

This is strange thing, i faced when added a Web Api controller inside an area of my production code.
I was using the defualt Web Api route pattern in WebApiConfig.cs

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);

Unfortunately when i tried to access the path via Jquery Ajax, I got the path not found exception.

This was the path i tried.
http://localhost:56109/api/MySecond

Ok, so i thought as my API controller is under an Area, i should try this way.

http://localhost:56109/api/MyArea/MySecond

Ooops!! still path not found, hmm. I added below code in my AreaRegistraion.Cs file.
Don’t forget to add refrence of “System.Web.Http”

context.Routes.MapHttpRoute(
"FileUpload",
"MyArea/api/{controller}/{id}",
new { AreaName = "MyArea", id = UrlParameter.Optional }
);

Wow now this path is working fine “http://localhost:56109/api/MyArea/MySecond

NB: This was experience in a production app developed with MVC 5 and VS 2013, Anyway i was not able to reproduce this in VS 2015.
As far as my understanding Web Api controllers and routing is independent of MVC Area.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s