![](/img/trans.png)
[英]Catch all routes not working after update Asp.Net WebApi 5.2.2 to 5.2.7
[英]ASP.NET WebApi not working. All routes return 404
我有一个asp.net web api, Unity
是我的依赖解析器, OWIN
是OAuth身份验证。
我使用Visual Studio“添加新项” -menu创建一个Startup.cs
,选择OWIN Startup类 :
[assembly: OwinStartup(typeof(MyNameSpace.Startup))]
namespace MyNameSpace
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
WebApiConfig.Register(config);
config.DependencyResolver = new UnityHierarchicalDependencyResolver(UnityConfig.GetConfiguredContainer());
app.UseWebApi(config);
}
}
}
我的WebApiConfig.cs
看起来像这样:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
现在,当我启动应用程序时,我得到一个Forbidden响应,默认URL为http://localhost:port/
。 web api托管在http://localhost:port/api/
。 当我在应用程序中请求此URL或任何控制器时,它会以Not Found响应。
另外,当我在Startup
类的Configuration
方法中放置一个断点时; 一旦我启动应用程序,它会显示以下内容(我不知道它是否相关):
我无法弄清楚出了什么问题。 它昨晚工作,我是唯一一个一直致力于这个项目的人。 我唯一做的就是从NuGet
添加OData
引用,但是一旦我确定api不能正常工作,我就再次删除它们。
编辑:
我应该补充一点,当我将鼠标悬停在应用程序上时,我在应用程序中设置的任何断点当前都显示相同的消息,因此它可能毕竟是相关的。
编辑2:
这是EmployeeController.cs
的摘录:
[Authorize]
public class EmployeeController : ApiController
{
private readonly IEmployeeService _service;
public EmployeeController(IEmployeeService employeeService)
{
_service = employeeService;
}
[HttpGet]
[ResponseType(typeof(Employee))]
public IHttpActionResult GetEmployee(string employeeId)
{
var result = _service.GetEmployees().FirstOrDefault(x => x.Id.Equals(employeeId));
if (result != null)
{
return Ok(result);
}
return NotFound();
}
[HttpGet]
[ResponseType(typeof (IQueryable<Employee>))]
public IHttpActionResult GetEmployees()
{
return Ok(_service.GetEmployees());
}
...
编辑3
按照建议重新启动Visual Studio后,我可以确认断点警告仍然存在并显示在整个应用程序中:
编辑4
删除OWIN
引用和Startup.cs
,应用程序现在恢复生机。 我能够再次放置断点并进行api调用。 这是怎么回事?
WebAPI操作方法基于HTTP Verb。
如果要命名HTTP谓词以外的操作方法,则需要查看“ 属性路由” 。
在您的示例中,您使用的是简单的HTTP谓词。 如果是这样,你只需要Get 。
public class EmployeeController : ApiController
{
// GET api/employee
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/employee/5
public string Get(int id)
{
return "value";
}
}
关于断点没有参与的一点,我自己就有这个问题。 意识到在我将应用程序发布到Web服务器之后,VS2013实际上已根据我用于发布的web.config转换更新了我的web.config,并关闭了调试(根据我的转换)。 可能是我是一个新手,这是正确的行为,但这不是理想的行为! :)这篇文章很老,我知道,但如果它能帮助任何有相同症状的人,那就太棒了。
我有同样的问题,所有端点返回404.我注意到WebApiConfig.Register从未调用过。 因此,请确保调用它,如果项目中有Global.asax文件(就像我的情况一样),请确保在Application_Start上启用了此调用:
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.