API补丁方法返回了错误的请求400

时间:2019-10-20 18:41:05

标签: c# postman httpclient asp.net-core-webapi http-patch

我正在使用.net核心Web API。我的API控制器类中的PATCH方法如下,

[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如下,

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

我从邮递员那里调用了API,并返回了400 BadRequest。

enter image description here enter image description here

我将断点放置在Controller方法中,但没有命中。在我从方法参数breakpoin hit中删除[FromBody] testClass msg而没有返回400之后。为什么当我使用[FromBody] testClass msg时它返回400?以及如何从HTTP客户端调用此控制器方法?

我尝试了这个,它还返回了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();

我该如何解决?请帮我。我删除了上一个问题,这是我的真正问题

已更新:

我将邮递员的请求更改为。

enter image description here

之后,它的工作原理。但是当我通过http客户端代码调用它时,它提供了400 BadRequest。如何通过http客户端提供JSON正文正确的方法

2 个答案:

答案 0 :(得分:1)

可以请您尝试一下。

[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);
 }
}

答案 1 :(得分:1)

使用FromBody时,您需要使用json而不是表单数据发送请求。您可以如下更改邮递员:

1。将ContentType更改为application/json

enter image description here

2。将Body更改为raw并选择样式JSON:

enter image description here

更新:

您需要像下面那样更改json:

string json = "{\"body\":\"sample text\"}";
相关问题