【问题标题】:Web API POST method returns HTTP/1.1 500 Internal Server ErrorWeb API POST 方法返回 HTTP/1.1 500 内部服务器错误
【发布时间】:2013-09-08 06:00:07
【问题描述】:

正如标题所说,我在使用 Web API 的 post 方法时出现 500 内部服务器错误。 Get 方法工作正常,只是在 POST 中出错。

我正在使用提琴手发送帖子请求:

响应标头: HTTP/1.1 500 内部服务器错误

请求标头: 用户代理:提琴手 主机:本地主机:45379 内容类型:应用程序/json内容长度:41 内容长度:41

请求正文: {"iduser"="123456789","username"="orange"}

这是我的 post 方法代码:

     // POST api/User
     public HttpResponseMessage Postuser(user user)
     {
        if (ModelState.IsValid)
        {
            db.users.Add(user);
            db.SaveChanges();

            HttpResponseMessage response =R  equest.CreateResponse(HttpStatusCode.Created, user);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = user.iduser }));
            return response;
       }
       else
        {
            return Request.CreateResponse(HttpStatusCode.BadRequest);
        }
    }

Sooooooo 可能出了什么问题?为什么它不允许我发帖?

【问题讨论】:

  • 那么您是否尝试过在调试器打开的情况下运行它,看看您的请求发生了什么?这似乎是找出可能出错的必要的第一步。
  • 您的请求正文有错字/您在用户 ID 后缺少引用 "
  • 是的,我在 post 方法上使用了断点,但它们没有被命中。

标签: web-services rest asp.net-mvc-4 asp.net-web-api


【解决方案1】:

您帖子中的数据不是有效的 JSON 对象,这是模型绑定器所期望的(内容类型:application/json)。

{"iduser"="123456789","username"="orange"}

尝试将您的 = 替换为 : 并查看您的情况。您的代码可以在我的机器上运行,并在请求中进行这些更改。

POST http://localhost:20377/api/test/Postuser HTTP/1.1
Host: localhost:20377
Connection: keep-alive
Content-Length: 42
User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.101 Safari/537.36
Origin: chrome-extension://fhjcajmcbmldlhcimfajhfbgofnpcjmb
Content-Type: application/json
Accept: */*
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-GB,en;q=0.8,en-US;q=0.6,nb;q=0.4,de;q=0.2

{"iduser":"123456789","username":"orange"}

【讨论】:

  • 就我而言,我在两个不同的控制器中使用相同的 URL,但它们的请求正文不同。
猜你喜欢
  • 2015-11-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-05-26
  • 2017-10-28
  • 1970-01-01
  • 2023-02-20
相关资源
最近更新 更多