加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

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

发布时间:2020-12-16 06:38:46 所属栏目:asp.Net 来源:网络整理
导读:我花了相当多的时间试图让Web API属性路由工作,而我得到的只是404错误,无论我尝试什么. 我有一个简单的ApiController尝试在api / hello / {number}和hello / {number}定义一个HttpGet: public class HelloController : ApiController{ public class Hello {
我花了相当多的时间试图让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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读