这是我的问题,我想通过POST
请求接收客户端的用户名和密码。
代码看起来很简单,但是不起作用
LoginController.cs
:
public class LoginController : ApiController
{
[HttpPost]
[ActionName("Login")]
[Route("api/{controller}")]
public HttpResponseMessage Login([FromBody] LoginJson json)
{
return Request.CreateResponse(HttpStatusCode.OK);
}
}
LoginJson.cs
形式:
public class LoginJson
{
public string Username { get; set; }
public string Password { get; set; }
}
带有ajax
的{{1}}请求,我不想更改URL,因为我想使用3个URL jQuery
,/api/Login
和/api/Method1
3种不同的控制器:
/api/Method2
API的路由,位于$.ajax({
url: '/api/Login',
type: 'POST',
dataType: "json",
contentType: "application/json, charset=utf-8",
data: JSON.stringify({
Username: username,
Password: password,
}),
...
});
中:
Global.asax.cs
我收到错误protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalFilters.Filters.Add(new HandleErrorAttribute());
RouteTable.Routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
RouteTable.Routes.MapRoute(...)
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}",
defaults: new {action = RouteParameter.Optional}
);
}
。
我将更改404 (Not Found)
文件。
答案 0 :(得分:2)
您只是不执行任何操作而调用控制器,并且由于未定义默认操作,因此会出现404错误。
在jQuery中,您可以执行以下操作:
url: '/api/Login/Login'
或通过添加以下标记来更改路由:
[Route("api/login")]
或者在RouteConfig.cs中,这应该在设置其他路由(包括通用路由)之前完成。
routes.MapRoute("Login", "Login/{action}",
defaults: new { controller = "Login", action = "Login" });
答案 1 :(得分:0)
没有api/login
您可以这样做:
[ActionName("api/login")]
public HttpResponseMessage Login([FromBody] LoginJson json)
{
return Request.CreateResponse(HttpStatusCode.OK);
}