正如标题所说,我在使用 Web API 的 post 方法时出现 500 内部服务器错误。 Get 方法工作正常,只是在 POST 中出错。
我正在使用 fiddler 发送帖子请求:
响应 header :
HTTP/1.1 500 内部服务器错误
请求 header :
用户代理: fiddler
主机:本地主机:45379
内容类型:应用程序/json内容长度:41
内容长度:41
请求正文:
{"iduser"="123456789","用户名"="橙色"}
这是我的 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 可能出了什么问题?为什么它不允许我发布?
最佳答案
您帖子中的数据不是有效的 JSON 对象,这是模型绑定(bind)器所期望的(内容类型: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"}
关于web-services - Web API POST 方法返回 HTTP/1.1 500 内部服务器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18618745/