Search code examples
c#asp.net-mvcasp.net-mvc-routing

MVC Routing (like WebAPI)


I know this sounds like a daft question but is there a way to 'mimic' WebAPI routing style (i.e maybe using the [HttpPost] decoration etc) for a MVC Controller. The gist of my problem is I have a 'container' MVC site. This contain in PreLoad loads up other MVC sites within the areas folder and incorporates them into itself. So it basically acts as a Plugin system. This all works great however I need to add in an API for this site which I thought would be a lot easier just if I made the API as another plugin.

I am using Ninject in my site which again works great getting the dependancies from the plugins all perfectly. The issue is that Ninject automatically detects the MVC Controllers but not the WebAPI ones and I've found out you can't have one project doing both WebAPI and MVC with Nijnect. So my next option is to try and mimic WebAPI within MVC (after all, they are based upon the same thing really.)

I initially thought this would be really easy, default the action name to 'Index' in the routing and them just put the 'AcceptVerbs' decoration on each method. Of course it didn't work.

Does anyone know how I would go about or an alternative to creating something like a RestAPI using only the MVC side (not switching to WebAPI)?


Solution

  • In your RouteConfig.cs file, you can specify which HTTP verb goes to which action by passing an HttpMethodContraint:

    routes.MapRoute(
    "route that matches only GETs for your url",
    "your url",
    new { controller = "some controller", action = "some action" },
    new { httpMethod = new HttpMethodConstraint("GET") });
    

    This will allow you to define routes to your controller that will mimic WebAPI.