在web api中从POST获得404响应?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (63)

我在我的Web api控制器中执行以下操作:

 // POST api/<controller>
    [AllowAnonymous]
    [HttpPost]
    public bool Post(string user, string password)
    {
         return true; 
    }

使用fiddler或测试jQuery脚本触发它时,出现以下404错误状态错误:

"Message":"No HTTP resource was found that matches the request URI 'http://localhost/amsi-v8.0.0/api/account'.","MessageDetail":"No action was found on the controller 'Account' that matches the request."}

我的http路由如下:

            RouteTable.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

提问于
用户回答回答于

调用该特定的操作方法。在你的情况下

/api/account?user=Foo&password=bar

如果你想要在请求体内获取这些值而不是查询字符串,只需创建一个User对象并相应地发送请求:

public class User { 
    public string Name {get;set;}
    public string Password {get;set;}
}

请求:

POST http://localhost:8181/api/account HTTP/1.1

Content-Type: application/json

Host: localhost:8181

Content-Length: 33

{"Name": "foo", "Password":"bar"}

你操作方法应该如下所示:

public HttpResponseMessage Post(User user) {

    //do what u need to do here

    //return back the proper response.
    //e.g: If you have created something, return back 201

    return new HttpResponseMessage(HttpStatusCode.Created);
}
用户回答回答于

发布一个json时,在模型文件夹中创建类,如下所示

public class Credential
{
    public string username { get; set; }
    public string password { get;set; }
}

更改参数

[HttpPost]
public bool Post(Credential credential)
{
     return true; 
}

扫码关注云+社区