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 我的帖子也不起作用. 解决方法
您的MVC路由优先于您的API路由.因为您正在使用捕获MVC端的所有路由(“{controller} / {action} / {id}”),并且它首先被注册,所以您的路由将始终寻找名为api或hello的mvc控制器,因为那是它匹配的路线.
尝试在您的Global.asax中将您的api注册移到MVC路由注册之上: GlobalConfiguration.Configure(WebApiConfig.Register); //then RouteConfig.RegisterRoutes(RouteTable.Routes); (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- asp.net-mvc – 如何在VS2012 MVC4项目中设置Ext.NET 2.0?
- 如何为ASP.NET Core Angular应用程序设置默认端口
- asp.net – 如何跨服务器场实现锁定?
- entity-framework – ASP.NET Web API中DbContext的推荐生命
- asp.net – 如何以二进制格式下载存储在SQL DB中的文件
- asp.net-mvc – TempData keep()vs peek()
- asp.net-web-api – 随着SerilogWeb.Owin停产,是否有“官方
- asp.net-web-api – 从ExceptionLogger引用操作参数
- asp.net – 从单独的配置文件中读取设置
- ASP.NET Ajax客户端框架无法加载.将ScriptManager放在空白页
推荐文章
站长推荐
- asp.net-web-api – 密码更改时如何使OAuth令牌无
- asp.net – Web部署项目的更好替代品
- asp.net – 存储Web应用程序项目组合参考的位置?
- asp.net – Web.Config文件中的多行文本
- asp.net-mvc – 允许asp.net mvc 2控制器名称的U
- asp.net-mvc – 在asp.net mvc中,单个项目与多个
- asp.net-mvc-4 – 如何在MVC4中呈现远程ReportVi
- asp.net-core – 我可以提交MVC6视图组件吗?
- asp.net-mvc-3 – Mini Profiler不渲染脚本
- asp.net – 实体框架与存储过程
热点阅读