[英]WebApi Routing causes 404 (Not Found) response
So, this is a simple one. 因此,这很简单。 I have done this in the past. 我过去曾经做过。 But, it seems that I am missing something. 但是,似乎我缺少了一些东西。
WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Attribute routing.
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Global.asax.cs
protected void Application_Start(object sender, EventArgs e)
{
GlobalConfiguration.Configure(WebApiConfig.Register);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
SomeController.cs
[RoutePrefix("api")]
public class SomeController: ApiController
{
[Route("some")]
[HttpGet]
private HttpResponseMessage GetSome(HttpRequestMessage request)
{
...
}
}
Now, when I call: http://localhost:54699/api/some
, I get the following 404
: 现在,当我呼叫: http://localhost:54699/api/some
,我得到以下404
:
{ "Message": "No HTTP resource was found that matches the request URI ' http://localhost:54699/api/some '.", "MessageDetail": "No type was found that matches the controller named 'some'." {“ Message”:“未找到与请求URI'http:// localhost:54699 / api / some '匹配的HTTP资源。”,“ MessageDetail”:“未找到与名为'some'的控制器匹配的类型。 “ } }
Folder structure: 资料夹结构:
Why is your controller method private this should be public 为什么您的控制器方法是私有的,这应该是公开的
[RoutePrefix("api")]
public class SomeController: ApiController
{
[Route("some")]
[HttpGet]
public HttpResponseMessage GetSome(HttpRequestMessage request)
{
...
}
}
Try to move GlobalConfiguration.Configure(WebApiConfig.Register);
尝试移动GlobalConfiguration.Configure(WebApiConfig.Register);
after MVC's FilterConfig
. 在MVC的FilterConfig
。 This is a standard caveat with WebAPI attribute routing. 这是WebAPI属性路由的标准警告。
you have /api in your routing configuration file. 您的路由配置文件中包含/ api。
you have mentioned /api as route prefix for controller and then action is "some". 您已经提到/ api作为控制器的路由前缀,然后操作就“有些”了。
the uri to "some" should be uri到“一些”应该是
http://localhost:<port>/api/api/some
[RoutePrefix("api/some")]
public class SomeController: ApiController
{
[HttpGet]
public HttpResponseMessage GetSome(HttpRequestMessage request)
{
...
}
}
You method GetSome is private. 您的方法GetSome是私有的。 Also, I'll modify the RoutePrefix attribute as in the code snippet to avoid rewriting the Route Attribute on each method. 另外,我将像代码片段中一样修改RoutePrefix属性,以避免在每个方法上重写Route属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.