ca9163d9
ca9163d9

Reputation: 29209

Asp.Net Core Web Api bug? "Put" cannot got value for the second parameter?

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

Answers (4)

cheergo
cheergo

Reputation: 1

You need to put your parameter this way:

{"id":"B161","myId":"B161"}

Upvotes: 0

ca9163d9
ca9163d9

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

PmanAce
PmanAce

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

Vincent Lerouvillois
Vincent Lerouvillois

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

Related Questions