Web API POST method returns HTTP/1.1 500 Internal

2020-06-17 05:03发布

As the title says i have got a 500 internal server error when using post method of a Web API. The Get method is working fine, just getting error in POST.

I am using fidler to send post request :

Response Header: HTTP/1.1 500 Internal Server Error

Request Header: User-Agent: Fiddler Host: localhost:45379 Content-Type: application/jsonContent-Length: 41 Content-Length: 41

Request Body: {"iduser"="123456789","username"="orange"}

Here is my code for post method:

     // 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 what could have possibly gone wrong? Why its not allowing me to POST?

1条回答
该账号已被封号
2楼-- · 2020-06-17 05:46

The data in your post is not a valid JSON-object, which is what the model binder is expecting (Content-Type: application/json).

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

Try replacing your = with : and see how you get on. Your code works on my machine with those alterations in the request.

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"}
查看更多
登录 后发表回答