c# – ASP.NET WebApi无法正常工作.所有路线返回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 Verb以外的操作方法,则需要查看Attribute Routing.

在您的示例中,您使用的是简单的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";
    }
}
点赞