asp.net - 无法启用/工作的 Web API 属性路由

标签 asp.net asp.net-mvc asp.net-web-api asp.net-web-api-routing

我花了相当多的时间试图让 Web API 属性路由正常工作,无论我尝试什么,我得到的都是 404 错误。

我有一个简单的 ApiController 试图在 api/hello/{number} 定义一个 HttpGet和 hello/{number} :

public class HelloController : ApiController
{
    public class Hello
    {
        public string user { get; set; }
        public string password { get; set; }
    }

    [Route("api/hello/{number}")]
    [Route("hello/{number}")]
    [HttpGet]
    public IEnumerable<Hello> GetStuff(int number)
    {
        var response = Request.CreateResponse(HttpStatusCode.Created, number);
        return null;
    }

    [Route("api/hello")]
    [HttpPost]
    public HttpResponseMessage PostHello(Hello value) 
    {
        var response = Request.CreateResponse(HttpStatusCode.Created, value);
        return response;
    }
}

我将此作为我的 RouteConfig,启用属性路由:
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        routes.MapMvcAttributeRoutes();

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

WebAPI 配置:
public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
    }
}

最后,这是我注册 WebApiConfig 的 Application_Start():
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
        GlobalConfiguration.Configure(WebApiConfig.Register);
    }

有没有人看到我想念的东西?对于以下所有情况,我收到 404 错误(无法在 GetStuff() 中找到断点):
  • http://localhost/api/hello
  • http://localhost/api/hello/1
  • http://localhost/hello
  • http://localhost/hello/2

  • 我的帖子也不起作用。

    最佳答案

    您的 MVC 路由优先于 API 路由。因为您在 MVC 端使用了一个 catch all 路由( "{controller}/{action}/{id}" ),并且它首先被注册,所以您的路由将始终寻找一个名为 api 的 mvc Controller 。或 hello ,因为那是它匹配的路线。

    尝试将 api 注册移到 Global.asax 中的 MVC 路由注册上方:

    GlobalConfiguration.Configure(WebApiConfig.Register);
    //then
    RouteConfig.RegisterRoutes(RouteTable.Routes);
    

    关于asp.net - 无法启用/工作的 Web API 属性路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27493525/

    相关文章:

    c# - 为什么 SignalR 会多次更改函数?

    c# - mvc web api中文件的真实物理路径

    asp.net - RedirectToRoute 应该如何使用?

    c# - 关闭浏览器时运行sql查询

    jquery - 将从数据库检索到的图像显示到图像控件

    c# - ReportViewer 控件不显示报告

    c# - 尝试读取结果集时遇到 fatal error 。 MySQL 网站

    asp.net-mvc - 检查上传的文件是否是 C# ASP.NET MVC 中的图像

    c# - 使用 OWIN 启动类时,如何在注册我的依赖项后处理我的 CaSTLe Windsor 容器?

    c# - .NET Web API - 添加日志记录