ASP.NET WebApi无法正常工作。所有路线返回404

时间:2015-05-05 17:58:29

标签: c# asp.net odata unity-container owin

我有一个asp.net web api,Unity作为我的依赖解析器,OWIN用于OAuth身份验证。

我使用Visual Studio“添加新项”菜单创建Startup.cs,选择 OWIN启动类

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

现在,当我启动应用程序时,我得到了一个禁止响应默认网址http://localhost:port/。网络API位于http://localhost:port/api/。当我在应用程序中请求此网址或任何控制器时,它会以未找到进行响应。

此外,当我在Configuration类的Startup方法中放置断点时;一旦我启动应用程序,它会显示以下内容(我不知道它是否相关):

message

我无法弄清楚出了什么问题。它昨晚工作,我是唯一一个一直致力于这个项目的人。我唯一做的就是添加来自OData的{​​{1}}引用,但是一旦我确定api无法正常工作,我就会再次删除它们。

修改

我应该补充一点,当我将鼠标悬停在应用程序上时,我在应用程序中设置的任何断点当前显示相同的消息,所以它可能毕竟是相关的。

编辑2:

这是摘自NuGet

EmployeeController.cs

编辑3

按照建议重新启动Visual Studio后,我可以确认断点警告仍然存在并显示在整个应用程序中:

breakpoint in controller

编辑4

删除[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()); } ... 引用和OWIN,应用程序现在恢复生机。我能够再次放置断点并进行api调用。发生了什么事?

2 个答案:

答案 0 :(得分:2)

WebAPI操作方法基于HTTP Verb。

如果您想要命名除HTTP谓词以外的操作方法,您需要查看Attribute Routing

在您的示例中,您使用的是简单的HTTP谓词。如果是这样,您只需获取

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

答案 1 :(得分:0)

我遇到了同样的问题,所有端点都返回404。我注意到从未调用过WebApiConfig.Register。 因此,请确保已调用它,并且如果您的项目中有Global.asax文件(例如我的情况),请确保已在Application_Start上启用此调用:

    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);          
    }
相关问题