API Patch 方法返回错误请求 400

tho*_*san 5 c# httpclient http-patch postman asp.net-core-webapi

我正在使用 .net core 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);
    }
}
Run Code Online (Sandbox Code Playgroud)

testClass如下,

public class testClass
{
    public string body { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

我从邮递员调用 API,它返回 400 BadRequest。

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

我在控制器方法中放置了断点,但它没有命中。在我[FromBody] testClass msg从方法参数中删除了断点命中而不返回之后400。为什么我使用时它返回 400 [FromBody] testClass msg?我如何从 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();
Run Code Online (Sandbox Code Playgroud)

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

更新:

我将邮递员请求更改为。

在此输入图像描述

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

Ren*_*ena 2

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

1.将ContentType更改为application/json

在此输入图像描述

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

在此输入图像描述

更新:

您需要像下面这样更改您的 json:

string json = "{\"body\":\"sample text\"}";
Run Code Online (Sandbox Code Playgroud)