Reputation: 29209
I have a Put
action. The Http request value cannot be passed to the second parameter.
[HttpPut("{id}")]
public async Task<IActionResult> Put(string id, [FromBody]DPost value)
{
Console.WriteLine($"id: {id} value.MyId: {value.MyId}"); // id: B161 value.MyId:
return Ok(value); // breakpoint here - id has value but value.MyId is null?
}
The following is the definition of the class.
public class DPost
{
[Key]
public String MyId { get; set; }
}
The following shows the raw Http requests.
PUT http://localhost:5001/api/D2/B161 HTTP/1.1
Host: localhost:5001
Connection: keep-alive
Content-Length: 52
Accept: application/json, text/plain, */*
Origin: http://localhost:8082
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2840.99 Safari/537.36
Content-Type: application/json;charset=UTF-8
Referer: http://localhost:8082/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8
{"id":"B161","value":{"myId":"B161"}}
And its response is
HTTP/1.1 200 OK
Date: Thu, 01 Dec 2016 18:29:02 GMT
Content-Type: application/json; charset=utf-8
Server: Kestrel
Access-Control-Allow-Origin: *
Content-Length: 12
{"myId":null}
Is it a bug of Asp.net core? I also tried to change the parameter value
to a simple type int?
and changed the Http request and it still got null.
Upvotes: 1
Views: 137
Reputation: 29209
Wrong answer: value.Id
actually is assigned to first value {id:"first", value:{id: "second"}}
. It should got "second". Is it a bug?
I found a solution by changing the class DPost
to:
public class DPost
{
[Key]
public String Id { get; set; }
}
Why? Does it need to match the first parameter case insensitively?
Upvotes: 1
Reputation: 4353
Change the case of MyId to the following:
public class DPost
{
[Key]
public String myId { get; set; }
}
to match the json object:
{"id":"B161","value":{"myId":"B161"}}
Upvotes: 0
Reputation: 371
Add [FromBody]
like this:
public async Task<IActionResult> Put(string id, [FromBody]DPost value)
It tells the engine to retrieve the object from the body of the request.
Upvotes: 0