【问题标题】:HttpRequestMessage.Content is null in receiving Controller actionHttpRequestMessage.Content 在接收控制器动作时为空
【发布时间】:2019-01-30 18:13:32
【问题描述】:

我看过一些类似的帖子,但都有一些不适用于我的案例的相关细节。我有一个现有的带有注册方法的购物者服务。它基于 .NET Framework 4.6.1 Web API 构建。我有许多工作场景,其中另一个 .NET Framework 4.6.1 Web API 服务使用 HttpClient 和 HttpRequestMessage 调用 Shopper 服务。我使用 GET、PUT 和 POST 方法执行此操作,并使用

成功地将数据传递给 PUT 和 POST 方法
request.Content = new ObjectContent<MemberAddress>(memberAddress, new System.Net.Http.Formatting.JsonMediaTypeFormatter());

我现在正在开发一项新服务,该服务基于 ASP.NET Core Web API 构建。我正在尝试在 Shopper 服务中调用 POST 操作。我从 IHttpClientFactory.CreateClient 获取我的 HttpClient。我认为 HttpRequestMessage 设置与我的其他调用服务中的设置相同。

        var request = new HttpRequestMessage(HttpMethod.Post, updateShopperUrl);
        request.Content = new ObjectContent<MemberRegistration>(memberRegistration, new System.Net.Http.Formatting.JsonMediaTypeFormatter(), "application/json");

对服务的调用如下所示:

        var httpClient = _clientFactory.CreateClient();
        var response = await httpClient.SendAsync(request);

我可以在调用之前检查 request.Content.Value ,它包含我期望的对象/数据。另一端的控制器操作代码如下所示:

    [Route("{shopperId}/register")]
    [Route("~/api/shopper/{shopperId}/register")]
    [HttpPost]
    public IHttpActionResult RegisterNewMember(string shopperId, [FromBody] MemberRegistration memberRegistration)
    {

但 memberRegistration 参数始终为空。 [FromBody] 属性是最近添加的,试图解决这个问题,但它没有帮助。 FromBody 无论如何都应该是复杂对象参数的默认行为。我可以使用 Postman 发布到该端点,并且通过 memberRegistration 数据。

要么我只是遗漏了一些明显的东西,要么可能在等式的 ASP.NET Core 调用方面发生了一些不同的事情。

【问题讨论】:

    标签: asp.net-core asp.net-web-api2


    【解决方案1】:

    您似乎正在尝试发布 JSON 数据

    尝试稍微改变方法,看看是否会有所作为。

    var json = JsonConvert.SerializeObject(memberRegistration);
    
    var content = new StringContent(json, Encoding.UTF8,"application/json");
    
    var httpClient = _clientFactory.CreateClient();
    
    var response = await httpClient.PostAsync(updateShopperUrl, content);
    

    以上手动将对象序列化为 JSON 并将其发布到 Web API。

    ObjectContent 使用的格式化程序可能存在问题

    【讨论】:

    • 我不明白为什么我的原始代码不起作用,但您建议的方法确实有效。我的原始代码基本上是从我的 .Net Framework 服务之一复制而来的,我怀疑该代码和/或它所依赖的 NuGet 包以及与 .NET Core 的兼容性存在一些问题。
    • 我遇到了同样的问题,请解释为什么 ObjectContent 在 .NET Core 中不起作用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-23
    • 2020-05-22
    • 2016-01-13
    • 1970-01-01
    • 2023-02-03
    • 1970-01-01
    相关资源
    最近更新 更多