路由和定义的操作的Web API uri返回404



我不明白System.Web.Http方法属性是如何使用的。我有这个方法Logon在我的Auth web API控制器(ASP。. Net MVC 4):

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,没有查询参数。如果我为emailpassword参数设置默认值,则方法匹配。但我认为MVC足够聪明,可以将请求内容与操作参数相匹配。我真的需要读取内容流来找到参数值吗?

显然,web Api不可能将带有多个参数的post请求绑定到一个操作。最简单的解决方案是发送一个json对象并解析它。我的方法现在看起来像

[HttpPost]
public HttpResponseMessage Logon(JObject dto)
{
    dynamic json = dto;
    string email = json.email;
    string password = json.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");
}

见http://www.west-wind.com/weblog/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methods
和http://www.west-wind.com/weblog/posts/2012/Sep/11/Passing-multiple-simple-POST-Values-to-ASPNET-Web-API

最新更新