【问题标题】:Asp.Net Core 3.1 Model Binding Doesn't WorkAsp.Net Core 3.1 模型绑定不起作用
【发布时间】:2020-07-22 10:11:16
【问题描述】:

模型绑定在 asp.net core 3.1 版本上不起作用。我对以前的 dotnet 核心版本或 .net 框架版本没有问题。请有人帮助我。

最好的问候

JavaScript 代码:

var postData = { "createdFrom": "2020-07-18", "createdTo": "2020-07-19", "message": "test", "logLevel": "Error" };

fetch('/log/list', {
    method: "post",
    body: JSON.stringify(postData),
    headers: {
        "Content-Type": "application/json"
    }
})
.then(res => res.json())
.then(res => {
    console.log(res);
}).catch(err => {
    console.error(err);
});

C# 代码:

[HttpPost]
public IActionResult List([FromBody] LogSearchModel searchModel) // searchModel is null
{
    string rawBodyStr = "";
    using (StreamReader reader = new StreamReader(Request.Body, Encoding.UTF8))
    {
        rawBodyStr = reader.ReadToEndAsync().Result;
    }

    // rawBodyStr is null
}

public class LogSearchModel
{
    [DisplayName("Başlangıç tarihi")]
    [UIHint("DateNullable")]
    public DateTime? CreatedFrom { get; set; }

    [DisplayName("Bitiş tarihi")]
    [UIHint("DateNullable")]
    public DateTime? CreatedTo { get; set; }

    [DisplayName("Açıklama")]
    public string Message { get; set; }

    [DisplayName("Olay türü")]
    public int LogLevel { get; set; }
}

Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped<LogManager>();

        services.AddControllersWithViews();
    }

【问题讨论】:

    标签: asp.net-core


    【解决方案1】:

    您的LogLevel 是 int 类型,但您传递的是字符串数据。

    更改自:

    var postData = { "createdFrom": "2020-07-18", "createdTo": "2020-07-19", 
                     "message": "test", "logLevel": "Error" };
    

    收件人:

    var postData = { "createdFrom": "2020-07-18", "createdTo": "2020-07-19",
                     "message": "test", "logLevel": 1 };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-17
      • 1970-01-01
      • 2021-02-14
      • 1970-01-01
      • 2018-06-18
      • 1970-01-01
      相关资源
      最近更新 更多