.net core rest api post end - 从正文中读取查询字符串

.net core rest api post end - read query string from body

在 .net 核心 2.1 中,

在 HTTP post 端点上,

是否可以从正文中读取查询字符串参数?

示例请求正文:

name="zakie"&country="uswest"&state="加利福尼亚"

您可以像下面这样自定义 TextInputFormatter:

public class CustomInputFormatter : TextInputFormatter
{
    public CustomInputFormatter()
    {
        SupportedMediaTypes.Add(MediaTypeHeaderValue.Parse("text/plain"));
        SupportedEncodings.Add(Encoding.UTF8);
        SupportedEncodings.Add(Encoding.Unicode);
    }
    protected override bool CanReadType(Type type)
    {
        return type == typeof(TestModel);
    }
    public override async Task<InputFormatterResult> ReadRequestBodyAsync(
        InputFormatterContext context, Encoding effectiveEncoding)
    {
        var reader = new StreamReader(context.HttpContext.Request.Body, effectiveEncoding);
        var line = await reader.ReadToEndAsync();
        var split = line.Split("&".ToCharArray());
        var model = new TestModel();
        foreach (var item in split)
        {
            var list = item.Split("=");
            var value = list[1].Replace("\"", "");
            model.GetType()
                .GetProperty(list[0], BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance)
                .SetValue(model, value, null);
        }
        return await InputFormatterResult.SuccessAsync(model);
    }     
}

测试模型:

public class TestModel
{
    public string Name { get; set; }
    public string Country { get; set; }
    public string State { get; set; }
}

控制器:

public void Test([FromBody]TestModel model)
{
    //do your stuff..
}

注册服务:

services.AddMvc(options=> {
    options.InputFormatters.Insert(0, new CustomInputFormatter());
}).SetCompatibilityVersion(CompatibilityVersion.Version_2_1);

结果: