.netCore3.1後端擷取不到模型的兩種解決方式:
解決方式一:https://blog.csdn.net/weixin_46681279/article/details/106494700
解決方式二:
services.AddMvc(option =>
{
//參數類型不一緻時,處理方式。
//option.InputFormatters.Insert(0, new CustomFilter.RawRequestBodyFormatter());
})
/// <summary>
/// 該類主要是用于驗證如果輸入對象參數類型與綁定對象參數類型不一緻時,api接口會包錯誤。
/// 進行重新綁定資料,然後得到對象對應的資料類型
/// </summary>
public class RawRequestBodyFormatter : IInputFormatter
{
public RawRequestBodyFormatter()
{
}
/// <summary>
/// 做指定類型的處理
/// </summary>
/// <param name="context">上下文内容</param>
/// <returns></returns>
public bool CanRead(InputFormatterContext context)
{
if (context == null) throw new ArgumentNullException("argument is Null");
var contentType = context.HttpContext.Request.ContentType;
//if (string.IsNullOrEmpty(contentType) || contentType == "text/plain" || contentType == "application/octet-stream"||contentType=="application/json")
if (string.IsNullOrEmpty(contentType) ||contentType=="application/json")
return true;
return false;
}
/// <summary>
/// 讀取
/// </summary>
/// <param name="context"></param>
/// <returns></returns>
public async Task<InputFormatterResult> ReadAsync(InputFormatterContext context)
{
var request = context.HttpContext.Request;
var contentType = context.HttpContext.Request.ContentType;
if (contentType.ToLower() == "application/json")
{
using (StreamReader reader = new StreamReader(request.Body, Encoding.UTF8))
{
var content = await reader.ReadToEndAsync();
var type=context.ModelType.Assembly.GetType(context.ModelType.FullName);
var aaa= Newtonsoft.Json.JsonConvert.DeserializeObject(content, type);
return await InputFormatterResult.SuccessAsync(content);
}
}
return await InputFormatterResult.FailureAsync();
}
}