Asp.Net Core 3.1 模型绑定不起作用



模型绑定在asp.net核心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; }
}

启动.cs

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

您的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 };

最新更新