【问题标题】:Web API uri to routed and defined action returns 404路由和定义操作的 Web API uri 返回 404
【发布时间】: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,没有查询参数。如果我为 emailpassword 参数设置默认值,则该方法匹配。但我认为 MVC 足够聪明,可以将请求内容与操作参数相匹配。我真的需要读取内容流来查找参数值吗?

【问题讨论】:

  • 你有AuthController吗?那有Logon 方法吗?
  • 是的,定义了一个Auth控制器,第一个代码示例是从中提取出来的,就是Logon方法本身。
  • 那个方法上没有授权属性的认证吗?
  • 有一个自定义的 ActionFilterAttribute 用于查找自定义标头并在缺少时返回 401,但这不相关。删除它不会改变问题。

标签: asp.net-mvc post routes


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-01
    • 1970-01-01
    • 2014-11-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多