[英].net core rest api post end - read query string from body
在 .net 核心 2.1 中,
在 HTTP post端點上,
是否可以從正文中讀取查詢字符串參數?
示例請求正文:
name="zakie"&country="uswest"&state="california"
您可以像下面這樣自定義 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);
結果:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.