jac*_*ott 6 c# asp.net-mvc asp.net-web-api asp.net-web-api2
我有一个使用MVC和WebAPI2的Web应用程序.在匹配手动配置的MVC路由之前,我希望始终与WebAPI2属性路由匹配.我在打电话configuration.MapHttpAttributeRoutes()之前试过打电话,RouteConfig.RegisterRoutes(RouteTable.Routes)但这似乎不起作用.
有没有办法确保WebAPI2路由始终具有优先权?
试一试吧。使用VS创建一个新的控制器。确保它名为 someController,其中 some 是您的控制器的名称,它必须以“Controller”结尾。确保你的类继承 ApiController...
public class someController : ApiController
{
[Route("api/test/{name}"), HttpGet]
public string Router(string name)
{
return "Your name is: " + name;
}
}
Run Code Online (Sandbox Code Playgroud)
还要将其添加到您的 global.asax 文件中。
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();
}
Run Code Online (Sandbox Code Playgroud)
上面的api路由正在等待HttpGet,您也可以使用HttpPost,并使用FormDataCollection来获取发布的表单数据。请注意如何使用 {someparameter} 参数化您的 API
上面的内容相当简单,API控制器可以序列化大多数实现序列化的对象。如果没有可以使用NewtonSoft什么的。
| 归档时间: |
|
| 查看次数: |
110 次 |
| 最近记录: |