首页 > 解决方案 > API Patch 方法返回错误请求 400

问题描述

我正在使用.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);
    }
}

testClass如下,

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

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

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

我在 Controller 方法中放置了断点,但它没有命中。在我[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();

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

更新:

我将邮递员请求更改为。

在此处输入图像描述

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

标签: c#postmanhttpclientasp.net-core-webapihttp-patch

解决方案


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

1.将内容类型更改为application/json

在此处输入图像描述

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

在此处输入图像描述

更新:

你需要改变你的json,如下所示:

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

推荐阅读