是否有现成的方式将HTTP请求的整个主体绑定到ASP.NET Core控制器操作中的字符串参数?

问题描述 投票:1回答:1

摘要

给出了带有字符串主体“汉堡包”的HTTP请求我希望能够将请求的整个主体绑定到控制器操作的方法签名中的字符串参数。

当通过向相对URL string-body-model-binding-example/get-body发出HTTP请求来调用此控制器时,出现错误,并且从未调用该操作

控制器

using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;

namespace MyProject
{
    [Route("string-body-model-binding-example")]
    [ApiController]
    public class ExampleController: ControllerBase
    {
        [HttpPut("get-body")]
        public string GetRequestBody(string body)
        {
            return body;
        }
    }
}

证明问题的综合测试

using FluentAssertions;
using System;
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;

public class MyIntegrationTests : MyIntegrationTestBase
{
    [Fact]
    public async Task String_body_is_bound_to_the_actions_body_parameter()
    {
        var body = "hamburger";
        var uri = "string-body-model-binding-example/get-body";
        var request = new HttpRequestMessage(HttpMethod.Put, uri)
        {
            Content = new StringContent(body, Encoding.UTF8, "text/plain")
        };

        var result = await HttpClient.SendAsync(request); 
        var responseBody = await result.Content.ReadAsStringAsync();
        responseBody.Should().Be(body,
            "The body should have been bound to the controller action's body parameter");
    }
}

注:在上面的示例中,测试HttpClient是使用Microsoft.AspNetCore.Mvc.Testing https://docs.microsoft.com/en-us/aspnet/core/test/integration-tests?view=aspnetcore-3.1设置的。我在动作方法签名中具有POCO模型的其他控制器动作是可以到达的,所以我知道我尝试进行模型绑定的方式有问题。

编辑:我尝试过的事情:

  • 将[FromBody]添加到参数=> 415不支持的媒体类型
  • 从控制器中删除[ApiController] =>命中了动作,但主体为null
  • 向参数添加[FromBody]并从控制器中删除[ApiController] => 415不支持的媒体类型
  • 将[Consumes(“ text / plain”)]添加到不带[ApiController]和不带[FromBody]的动作中>
  • 发送具有上述任何组合的内容类型为application / json的请求=>错误或为空,具体取决于选项
  • 令我惊讶的是,字符串不是supported primitives之一

摘要给定一个带有字符串主体“汉堡包”的HTTP请求,我希望能够将请求的整个主体绑定到控制器动作的方法签名中的字符串参数。通话时...

c# asp.net-core model-binding
1个回答
0
投票

不确定是否可以通过框架手段实现,但是您可以为此创建自定义模型绑定器

© www.soinside.com 2019 - 2024. All rights reserved.