Make sure WebAPI2 routes are mapped before MVC routes

I have a web application that uses both MVC and WebAPI2. I would like requests to always match WebAPI2 attribute routes before mapping MVC routes to manual configuration. I tried calling configuration.MapHttpAttributeRoutes() before calling RouteConfig.RegisterRoutes(RouteTable.Routes) , but this does not work.

Is there a way to ensure that WebAPI2 routes always take precedence?

+6
source share
1 answer

Give it back. Use VS to create a new controller. Make sure it's called someController, where some is the name of your controller, it should end in "Controller". Make sure your class inherits ApiController ...

 public class someController : ApiController { [Route("api/test/{name}"), HttpGet] public string Router(string name) { return "Your name is: " + name; } } 

Also add this to your global.asax file.

  protected void Application_Start(object sender, EventArgs e) { GlobalConfiguration.Configuration.Formatters.XmlFormatter.SupportedMediaTypes.Clear(); //This will remove XML serialization and return everything in JSON. GlobalConfiguration.Configuration.MapHttpAttributeRoutes(); GlobalConfiguration.Configuration.EnsureInitialized(); } 

In the above example, the api route expects an HttpGet, you can also use HttpPost and use FormDataCollection to get the form data. Note how you can parameterize your APIs with {someparameter}

The above is quite simple, and the API controller can serialize most objects that implement serialization. If you can not use NewtonSoft or something like that.

0
source

Source: https://habr.com/ru/post/1013756/


All Articles