问题描述
在 .net core 2.1 中,
在 HTTP post 端点上,
是否可以从正文中读取查询字符串参数?
示例请求正文:
name="zakie"&country="uswest"&state="california"
解决方法
您可以自定义 TextInputFormatter,如下所示:
{0}
测试模型:
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..
}
结果: