Md Farid Uddin Kiron
Md Farid Uddin Kiron

Reputation: 22515

HTTP PUT Request Body Found Null In Web API Controller

I am trying to send a request with HTTP Verb [HttpPut] which reached to my controller but param which I have sent is Null. Have seen lot of stack Overflow same thread and tried out but cannot figure out... Weird!

Class I have Serialized

Content requestContent = new Content();
requestContent.Name = "Name";
requestContent.Value = "Value";

Here is my request body

private readonly HttpClient _httpClient;

public GetAzureResponseClient(HttpClient httpClient)
{
    _httpClient = httpClient ?? throw new ArgumentNullException(nameof(httpClient));
}

var requestBody = JsonConvert.SerializeObject(requestContent); 
var uri = new Uri("http://localhost:64288/api/ConnectUs/TestMethod");
var response = _httpClient.PutAsJsonAsync(uri, new StringContent(requestBody, Encoding.UTF8, "application/json")).Result;
client.DefaultRequestHeaders.Add("Authorization", "Basic" + "YourAuthKey");
var responseFromServer = await response.Content.ReadAsStringAsync();

My Web API Controller

public ActionResult<Content> TestMethod([FromBody]Content param)

Upvotes: 0

Views: 1424

Answers (3)

Daniel A. White
Daniel A. White

Reputation: 191036

You dont need to rewrap the object as JSON when using PutAsJsonAsync:

HttpClient client = new HttpClient();
var uri = new Uri("http://localhost:64288/api/ConnectUs/TestMethod");
var response = await client.PutAsJsonAsync(uri, requestContent); // LOOK HERE
client.DefaultRequestHeaders.Add("Authorization", "Basic" + "YourAuthKey");
var responseFromServer = await response.Content.ReadAsStringAsync();

Upvotes: 2

Mehrdad
Mehrdad

Reputation: 1731

you don't need extra serialization and you have to call the Async method with 'await'.

        HttpClient client = new HttpClient();
        client.DefaultRequestHeaders.Add("Authorization", "Basic" + "YourAuthKey");
        var uri = new Uri("http://localhost:64288/api/ConnectUs/TestMethod");
        var response = await client.PutAsJsonAsync(uri, requestContent);
        var responseFromServer = await response.Content.ReadAsStringAsync();

Upvotes: 1

Related Questions