加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-web-api – 为什么我在web api中从我的POST获得404响应

发布时间:2020-12-16 00:29:34 所属栏目:asp.Net 来源:网络整理
导读:我的Web api控制器中有以下操作: // POST api/controller [AllowAnonymous] [HttpPost] public bool Post(string user,string password) { return true; } 当使用fiddler或测试jQuery脚本来触发404状态时,我收到以下错误: {“消息”:“没有找到符合请求U
我的Web api控制器中有以下操作:
// POST api/<controller>
    [AllowAnonymous]
    [HttpPost]
    public bool Post(string user,string password)
    {
         return true; 
    }

当使用fiddler或测试jQuery脚本来触发404状态时,我收到以下错误:

{“消息”:“没有找到符合请求URI的HTTP资源”http://localhost/amsi-v8.0.0/api/account“。”,“MessageDetail”:“控制器上没有找到任何操作”帐户’符合请求。“}

我的http路由如下:

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

得到工作正常我在这里发现了另一个问题,它从IIS中删除WebDAV。我试过,还是一样的问题。

为什么我得到404?

解决方法

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

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);
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读