20

I have the following action in my Web api controller:

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

I am getting the following error with a 404 status when hitting it with either fiddler or a test jQuery script:

{"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."}

My http route is as follows:

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

Gets work fine. I found another question here which talks about removing WebDAV from IIS. I tried that, still same issue.

Why do I get a 404?

4

2 回答 2

38

ASP.NET Web API 中的默认操作选择行为也关心您的操作方法参数。如果它们是简单类型的对象并且它们不是可选的,则需要提供它们才能调用该特定的操作方法。在您的情况下,您应该发送一个针对 URI 的请求,如下所示:

/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

内容类型:应用程序/json

主机:本地主机:8181

内容长度:33

{“名称”:“foo”,“密码”:“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);
}
于 2012-07-27T09:07:39.303 回答
2

当我们发布一个 json 时,它需要一个类,所以像这样在模型文件夹中创建类

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

现在更改参数

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

现在尝试一切都会顺利进行

于 2015-07-12T01:48:52.960 回答