1

我不明白如何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,它返回一个404 not found带有以下 JSON 的:

{
"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 足够聪明,可以将请求内容与操作参数相匹配。我真的需要阅读内容流来查找参数值吗?

4

1 回答 1

0

Web Api 显然不可能将具有多个参数的发布请求绑定到操作。最简单的解决方案是发送一个 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

于 2013-05-06T09:17:56.387 回答