简体   繁体   English

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

[英]ASP.NET WebApi not working. All routes return 404

I have an asp.net web api with Unity as my dependency resolver and OWIN for OAuth authentication. 我有一个asp.net web api, Unity是我的依赖解析器, OWIN是OAuth身份验证。

I create a Startup.cs using the Visual Studio "Add New Item"-menu, choosing OWIN Startup class : 我使用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);
        }
    }
}

My WebApiConfig.cs looks like this: 我的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 }
    );
}

Now, when I start the application I get a Forbidden response for the default url which is http://localhost:port/ . 现在,当我启动应用程序时,我得到一个Forbidden响应,默认URL为http://localhost:port/ The web api is hosted at http://localhost:port/api/ . web api托管在http://localhost:port/api/ When I make a request for this url or any controller in the application it responds with Not Found . 当我在应用程序中请求此URL或任何控制器时,它会以Not Found响应。

Additionally, when I put a breakpoint in the Configuration method of the Startup class; 另外,当我在Startup类的Configuration方法中放置一个断点时; once I start up the application it displays the following (I don't know if it is relevant): 一旦我启动应用程序,它会显示以下内容(我不知道它是否相关):

信息

I can't figure out what's wrong. 我无法弄清楚出了什么问题。 It worked last night and I'm the only one who has been working on this project. 它昨晚工作,我是唯一一个一直致力于这个项目的人。 The only thing I've done is add OData references from NuGet , but I removed those again once I established that the api was not working. 我唯一做的就是从NuGet添加OData引用,但是一旦我确定api不能正常工作,我就再次删除它们。

EDIT: 编辑:

I should add that any breakpoint I set in the application currently displays the same message when I hover over it, so maybe it is relevant after all. 我应该补充一点,当我将鼠标悬停在应用程序上时,我在应用程序中设置的任何断点当前都显示相同的消息,因此它可能毕竟是相关的。

EDIT 2: 编辑2:

This is an excerpt from EmployeeController.cs : 这是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());
    }
...

EDIT 3 编辑3

After restarting Visual Studio as suggested I can confirm that the breakpoint warning persists and shows up accross the entire application: 按照建议重新启动Visual Studio后,我可以确认断点警告仍然存在并显示在整个应用程序中:

控制器中的断点

EDIT 4 编辑4

Removing OWIN references and Startup.cs , the application now springs back into life. 删除OWIN引用和Startup.cs ,应用程序现在恢复生机。 I am able to place breakpoints again and make api calls. 我能够再次放置断点并进行api调用。 What's going on? 这是怎么回事?

WebAPI Action Methods are based on HTTP Verb. WebAPI操作方法基于HTTP Verb。

If you want to name action method other than HTTP Verb, you want to look at Attribute Routing . 如果要命名HTTP谓词以外的操作方法,则需要查看“ 属性路由”

In your example, you are using simple HTTP Verb. 在您的示例中,您使用的是简单的HTTP谓词。 If so, you just need Get . 如果是这样,你只需要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";
    }
}

Just a point about the breakpoints not engaging, I had this problem myself. 关于断点没有参与的一点,我自己就有这个问题。 Realised that after I published the app to the web server, VS2013 had actually updated my web.config in accordance with my web.config transform I had for publish, and had turned off the debugging (as per my transform). 意识到在我将应用程序发布到Web服务器之后,VS2013实际上已根据我用于发布的web.config转换更新了我的web.config,并关闭了调试(根据我的转换)。 It may be me being a newb and this is the correct behaviour, but it wasn't the desired behaviour! 可能是我是一个新手,这是正确的行为,但这不是理想的行为! :) This post is old, I know, but if it helps anyone with the same symptoms, excellent. :)这篇文章很老,我知道,但如果它能帮助任何有相同症状的人,那就太棒了。

I had the same problem, which all endpoints returned 404. I notice that the WebApiConfig.Register never called. 我有同样的问题,所有端点返回404.我注意到WebApiConfig.Register从未调用过。 So make sure it is called, and if you have a Global.asax file on your project (like in my case) make sure you have this call enabled on Application_Start: 因此,请确保调用它,如果项目中有Global.asax文件(就像我的情况一样),请确保在Application_Start上启用了此调用:

    protected void Application_Start()
    {
        GlobalConfiguration.Configure(WebApiConfig.Register);          
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM