asp.net-mvc 所有 ASP.NET Web API 控制器都返回 404
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15556035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
All ASP.NET Web API controllers return 404
提问by Ted Nyberg
I'm trying to get an API Controller to work inside an ASP.NET MVC 4 web app. However, every request results in a 404and I'm stumped. :/
我正在尝试让 API 控制器在 ASP.NET MVC 4 Web 应用程序中工作。但是,每个请求都会导致404,我很难过。:/
I have the standard API controller route from the project template defined like:
我有来自项目模板的标准 API 控制器路由,定义如下:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
The registration is invoked in Global.asax:
在 Global.asax 中调用注册:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// Register API routes
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
I have a basic API controller like this:
我有一个像这样的基本 API 控制器:
namespace Website.Controllers
{
public class FavoritesController : ApiController
{
// GET api/<controller>
public IEnumerable<string> Get()
{
return new [] { "first", "second" };
}
// PUT api/<controller>/5
public void Put(int id)
{
}
// DELETE api/<controller>/5
public void Delete(int id)
{
}
}
}
Now, when I browse to localhost:59900/api/FavoritesI expect the Getmethod to be invoked, but instead I get a 404status code and the following response:
现在,当我浏览到localhost:59900/api/Favorites 时,我希望调用Get方法,但我得到的是404状态代码和以下响应:
<Error>
<Message>
No HTTP resource was found that matches the request URI 'http://localhost:59900/api/Favorites'.
</Message>
<MessageDetail>
No type was found that matches the controller named 'Favorites'.
</MessageDetail>
</Error>
Any help would be greatly appreciated, I'm losing my mind a little bit over here. :) Thanks!
任何帮助将不胜感激,我在这里有点失去理智。:) 谢谢!
回答by Eric Bishard
One thing I ran into was having my configurations registered in the wrong order in my GLobal.asax file for instance:
我遇到的一件事是我的配置在 GLobal.asax 文件中以错误的顺序注册,例如:
Right Order:
正确的顺序:
AreaRegistration.RegisterAllAreas();
WebApiConfig.Register(GlobalConfiguration.Configuration);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
Wrong Order:
错误的顺序:
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
WebApiConfig.Register(GlobalConfiguration.Configuration);
Just saying, this was my problem and changing the order is obvious, but sometimes overlooked and can cause much frustration.
只是说,这是我的问题,更改顺序很明显,但有时会被忽视,并会导致很多挫折。
回答by Zenilogix
Had essentially the same problem, solved in my case by adding:
有基本相同的问题,在我的情况下通过添加解决了:
<modules runAllManagedModulesForAllRequests="true" />
to the
到
<system.webServer>
</system.webServer>
section of web.config
web.config 的部分
回答by user4796368
I have been working on a problem similar to this and it took me ages to find the problem. It is not the solution for this particular post, but hopefully adding this will save someone some time trying to find the issue when they are searching for why they might be getting a 404 error for their controller.
我一直在研究与此类似的问题,我花了很长时间才找到问题所在。这不是这篇特定帖子的解决方案,但希望添加它可以节省一些人在寻找为什么他们的控制器可能会收到 404 错误时试图找到问题的时间。
Basically, I had spelt "Controller" wrong at the end of my class name. Simple as that!
基本上,我在班级名称的末尾拼错了“Controller”。就那么简单!
回答by Farhan Anwar
Add following line
添加以下行
GlobalConfiguration.Configure(WebApiConfig.Register);
in Application_Start()function in Global.ascx.csfile.
Application_Start()在Global.ascx.cs文件中的函数中。
回答by Aran Dekar
I had the same problem, then I found out that I had duplicate api controller class names in other project and despite the fact that the "routePrefix"and namespace and project name were different but still they returned 404, I changed the class names and it worked.
我遇到了同样的问题,然后我发现我在其他项目中有重复的 api 控制器类名称,尽管“routePrefix”和命名空间以及项目名称不同,但它们仍然返回 404,我更改了类名称并工作。
回答by BRass
Similar problem with an embarrassingly simple solution - make sure your API methods are public. Leaving off any method access modifier will return an HTTP 404 too.
一个令人尴尬的简单解决方案的类似问题 - 确保您的 API 方法是public. 离开任何方法访问修饰符也将返回 HTTP 404。
Will return 404:
将返回 404:
List<CustomerInvitation> GetInvitations(){
Will execute as expected:
将按预期执行:
public List<CustomerInvitation> GetInvitations(){
回答by Shakeer Hussain
Create a Route attribute for your method.
为您的方法创建一个 Route 属性。
example
例子
[Route("api/Get")]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
You can call like these http://localhost/api/Get
你可以像这样调用http://localhost/api/Get
回答by Morvael
For reasons that aren't clear to me I had declared all of my Methods / Actions as static - apparently if you do this it doesn't work. So just drop the staticoff
由于我不清楚的原因,我已将所有方法/操作声明为静态 - 显然,如果您这样做,它就不起作用。所以就static下车吧
[AllowAnonymous]
[Route()]
public static HttpResponseMessage Get()
{
return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
}
Became:-
变成了:-
[AllowAnonymous]
[Route()]
public HttpResponseMessage Get()
{
return new HttpResponseMessage(System.Net.HttpStatusCode.OK);
}
回答by Ted Nyberg
I'm a bit stumped, not sure if this was due to an HTTP output caching issue.
我有点困惑,不确定这是否是由于 HTTP 输出缓存问题。
Anyways, "all of a sudden it started working properly". :/ So, the example above worked without me adding or changing anything.
无论如何,“突然间它开始正常工作了”。:/ 所以,上面的例子没有我添加或改变任何东西。
Guess the code just had to sit and cook overnight... :)
猜猜代码只需要坐下来煮一夜...... :)
Thanks for helping, guys!
感谢您的帮助,伙计们!
回答by Kevin R.
Check that if your controller class has the [RoutePrefix("somepath")] attribute, that all controller methods also have a [Route()] attribute set.
检查您的控制器类是否具有 [RoutePrefix("somepath")] 属性,所有控制器方法是否也具有 [Route()] 属性集。
I've run into this issue as well and was scratching my head for some time.
我也遇到了这个问题,并且挠了一段时间。

