[英]ASP.NET Web API Route Controller Not Found
I am trying to post to the following Web API: 我想发布到以下Web API:
http://localhost:8543/api/login/authenticate
LoginApi (Web API) is defined below: LoginApi(Web API)定义如下:
[RoutePrefix("login")]
public class LoginApi : ApiController
{
[HttpPost]
[Route("authenticate")]
public string Authenticate(LoginViewModel loginViewModel)
{
return "Hello World";
}
}
WebApiConfig.cs: WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
Here is the error I get: 这是我得到的错误:
Request URL:http://localhost:8543/api/login/authenticate
Request Method:POST
Status Code:404 Not Found
Remote Address:[::1]:8543
Your controller name "LoginApi" needs to end in "Controller" in order for the framework to find it. 您的控制器名称“LoginApi”需要以“Controller”结尾,以便框架找到它。 For example: "LoginController"
例如:“LoginController”
Here is a good article which explains routing in ASP.NET Web API: http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api 这篇文章解释了ASP.NET Web API中的路由: http : //www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
You are using login
as your route prefix on your controller so trying to call 您正在控制器上使用
login
作为路由前缀,因此尝试呼叫
http://localhost:8543/api/login/authenticate
will not be found as this code 将不会被发现为此代码
[RoutePrefix("login")]
public class LoginApi : ApiController
{
//eg:POST login/authenticate.
[HttpPost]
[Route("authenticate")]
public string Authenticate(LoginViewModel loginViewModel)
{
return "Hello World";
}
}
will only work for 只会工作
http://localhost:8543/login/authenticate
You need to change your route prefix to 您需要将路由前缀更改为
[RoutePrefix("api/login")]
public class LoginApi : ApiController
{
//eg:POST api/login/authenticate.
[HttpPost]
[Route("authenticate")]
public string Authenticate(LoginViewModel loginViewModel)
{
return "Hello World";
}
}
Notice you are using both attribute routing on the controller/action and convention routing with config.Routes.MapHttpRoute. 请注意,您正在使用config.Routes.MapHttpRoute在控制器/操作和约定路由上使用属性路由。
config.Routes.MapHttpRoute will map the routes as per your definition " api/{controller}/{id}
". config.Routes.MapHttpRoute将根据您的定义“
api/{controller}/{id}
”映射路由。
While attribute routing, will map the routes based on how you've defined them: /login/authenticate
. 属性路由时,将根据您的定义方式映射路由:
/login/authenticate
。
Also, since you are using both attribute routing and convention routing, attribute routing takes presendence. 此外,由于您同时使用属性路由和约定路由,因此属性路由会占用优先级。 I would stick to using one or the other.
我会坚持使用其中一个。 Having both adds a bit of confusion as to what route will be used to access an action method.
两者都会增加一些关于将用于访问动作方法的路线的混淆。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.