【发布时间】:2013-05-06 08:09:38
【问题描述】:
我不明白System.Web.Http 方法属性是如何使用的。我在我的Auth web API 控制器(ASP.Net MVC 4)中有这个方法Logon:
public HttpResponseMessage Logon(string email, string password)
{
User user = UserSrv.Load(email);
if (user != null && user.CheckPassword(password))
return this.Request.CreateResponse<User>(HttpStatusCode.OK, user);
else
return this.Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid username or password");
}
WebApiConfig.cs 文件是默认的:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}
按原样,GET 方法返回405 method not allowed。就像我尝试过的 PUT、HEAD 和所有其他动词一样。但是对于 POST,它会返回一个带有以下 JSON 的 404 not found:
{
"Message": "No HTTP resource was found that matches the request URI 'http://localhost:8080/api/Auth/Logon'.",
"MessageDetail": "No action was found on the controller 'Auth' that matches the request."
}
如果在方法定义之前添加[HttpPost] 属性,我会得到完全相同的结果。使用HttpGet,当然 GET 请求是可以的。两个属性的组合不会改变任何东西。 POST 请求为何未正确路由?
编辑:
POST 请求不匹配,因为 Uri 是 http://localhost:8080/api/Auth/Logon,没有查询参数。如果我为 email 和 password 参数设置默认值,则该方法匹配。但我认为 MVC 足够聪明,可以将请求内容与操作参数相匹配。我真的需要读取内容流来查找参数值吗?
【问题讨论】:
-
你有
AuthController吗?那有Logon方法吗? -
是的,定义了一个Auth控制器,第一个代码示例是从中提取出来的,就是Logon方法本身。
-
那个方法上没有授权属性的认证吗?
-
有一个自定义的 ActionFilterAttribute 用于查找自定义标头并在缺少时返回 401,但这不相关。删除它不会改变问题。
标签: asp.net-mvc post routes