简体   繁体   中英

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.

在此处输入图像描述 在此处输入图像描述

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.

在此处输入图像描述

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

Could you please try this.

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

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 :

在此处输入图像描述

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

在此处输入图像描述

UPDATE:

You need change your json like below:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM