【问题标题】:Ensure that WebAPI2 routes are matched before MVC Routes确保 WebAPI2 路由在 MVC 路由之前匹配
【发布时间】:2017-05-19 01:05:51
【问题描述】:

我有一个同时使用 MVC 和 WebAPI2 的 Web 应用程序。在匹配手动配置的 MVC 路由之前,我希望请求始终与 WebAPI2 属性路由匹配。我曾尝试在致电RouteConfig.RegisterRoutes(RouteTable.Routes) 之前致电configuration.MapHttpAttributeRoutes(),但这似乎不起作用。

有什么方法可以确保 WebAPI2 路由始终具有优先权?

【问题讨论】:

  • Web API 路由的约定是在路由前加上“api”,甚至是版本“v1”。这会将它们与 MVC 路由隔离,那么除非您在 MVC 和 Web API 之间共享约定,否则为什么要关心顺序?

标签: c# asp.net-mvc asp.net-web-api asp.net-web-api2


【解决方案1】:

试一试。使用 VS 创建一个新的控制器。确保它被称为 someController,其中 some 是您的控制器的名称,它必须以“Controller”结尾。确保你的类继承了 ApiController...

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

在你的 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();
    }

上面的api路由在等待HttpGet,你也可以使用HttpPost,使用FormDataCollection来获取posted的表单数据。请注意如何使用 {someparameter}

参数化您的 API

上面的很简单,API控制器可以序列化大部分实现序列化的对象。如果没有可以使用 NewtonSoft 之类的。

【讨论】:

    猜你喜欢
    • 2012-07-13
    • 1970-01-01
    • 2014-06-14
    • 1970-01-01
    • 2018-11-01
    • 1970-01-01
    • 2011-10-25
    • 2015-01-10
    • 1970-01-01
    相关资源
    最近更新 更多