asp.net – 无法启用/正在运行Web API属性路由

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

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

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 }
        );
    }
}

WebAPIConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();
    }
}

最后,这是我的Application_Start(),我注册了WebApiConfig

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端的所有路由(“{controller} / {action} / {id}”),并且它首先被注册,所以您的路由将始终寻找名为api或hello的mvc控制器,因为那是它匹配的路线.

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

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

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....