Search code examples
c#postmanhttpclientasp.net-core-webapihttp-patch

Bad request 400 returns from API Patch method


I'm using .net core web api. in my API controller class have PATCH method as follows,

[HttpPatch("updateMessageTemplate/{templateId}")]
public IActionResult UpdateMessageTemplate([FromHeader] int tenantId, int templateId,[FromBody] testClass msg)
{
    try
    {
        //Some implementation is here
        return Accepted();
    }
    catch
    {
        return StatusCode(500);
    }
}

testClass as follows,

public class testClass
{
    public string body { get; set; }
}

I called the API from postman and its returns 400 BadRequest.

enter image description here enter image description here

I placed the breakpoint in Controller method, but its not hitting. after I removed the [FromBody] testClass msg from the method parameter breakpoin hit without return 400 . why its returns 400 when I use [FromBody] testClass msg ? And how can I call this controller method from the HTTP Client ?.

I tried this, its also returns 400 BadRequest

string serviceUrl = string.Format("{0}/notification/updateMessageTemplate/{1}", ConfigurationManager.AppSettings["LtApiUrl"], templateID);

string json = "[{\"body\":\"sample text\"}]";

HttpClient client = new HttpClient();
HttpMethod method = new HttpMethod("PATCH");
HttpRequestMessage message = new HttpRequestMessage(method, serviceUrl);

StringContent content = new StringContent(json, Encoding.UTF8, "application/json");
client.DefaultRequestHeaders.Add("tenantId", tenantId.ToString());
client.DefaultRequestHeaders.Add("Authorization", string.Format("bearer {0}", token));
message.Content = content;

var response = client.SendAsync(message).Result;               
return response.StatusCode.ToString();

How can I solve this? please help me. I deleted the previous question and this is my real problem

Updated:

I changed the postman request as.

enter image description here

after that its works. but when I call it through http client code its provides 400 BadRequest. how to provide JSON body correct way through http client


Solution

  • For you use FromBody,you need to send request with json instead of form data.You could change your postman like below:

    1.change the ContentType to application/json:

    enter image description here

    2.change the Body to raw and choose the style JSON:

    enter image description here

    UPDATE:

    You need change your json like below:

    string json = "{\"body\":\"sample text\"}";