【发布时间】:2021-12-29 18:42:07
【问题描述】:
我过去只是将简单的 json 对象发布到 ASP.NET MVC 控制器,绑定引擎会将主体解析为方法的简单参数:
{
"firstname" : "foo",
"lastname" : "bar"
}
我可以有一个像这样的 MVC 控制器:
public method Blah(string firstname, string lastname) {}
firstname 和 lastname 会自动从 Json 对象中拉出并映射到简单参数。
我已将具有相同方法签名的后端部分移至 .NET Core 5.0,但是,当我发布相同的简单 JSON 对象时,我的参数为空。我什至尝试对每个参数执行[FromBody],但它们仍然为空。直到我创建了一个包含参数名称的额外类,模型绑定才起作用:
public class BlahRequest
{
public string firstname { get; set;}
public string lastname { get; set; }
}
然后我必须将我的方法签名更新为如下所示:
public method Blah([FromBody]BlahRequest request) { }
现在,该请求具有从发布请求中填写的属性firstname 和lastname。
是否有模型绑定设置,我可以返回从简单的 Json 对象绑定到方法的参数?还是我必须更新所有方法签名以包含具有属性的类?
如何调用 web api 方法
原始应用程序是用 Angular 编写的,但我可以通过一个简单的 Fiddler 请求重新创建它:
POST https://localhost:5001/Blah/Posted HTTP/1.1
Host: localhost:5001
Connection: keep-alive
Accept: application/json, text/plain, */*
Content-Type: application/x-www-form-urlencoded
{"firstname":"foo","lastname":"bar"}
在以前版本的 .Net 框架中,控制器的方法会自动解析这些值。现在,在核心上,它需要传入一个模型。我尝试了 application/json、multipart/form-data 和 application/x-www-form-urlencoded 作为 Content-type,它们都以 null 结尾价值观。
最小的 .Net Core 项目
public class Startup {
public Startup(IConfiguration configuration) {
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services){
services.AddControllers();
}
public void Configure(IApplicationBuilder app, IWebHostEnvironment env) {
app.UseHttpsRedirection();
app.UseRouting();
app.UseEndpoints(endpoints => { endpoints.MapControllers(); });
}
}
[Route("[controller]/[action]")]
public class BlahController : ControllerBase {
public object Posted(string firstname, string lastname) {
Console.WriteLine(firstname);
Console.WriteLine(lastname);
return true;
}
}
【问题讨论】:
-
你在这方面有什么进展吗?我有一个类似的问题,我正在尝试移植 .NET Framework 代码,其中我有许多控制器方法,例如
public method Blah(string firstname, string lastname) {}并且我试图以{"firstname": "John", "lastname": "Smith"}格式传递 JSON,除非我添加,否则该方法不会绑定它们中间模型 -
@Campbell 是的,我做到了。我在下面发布的答案是我用来将 .Net Framework 4.8 代码移植到 .Net Core 而无需重写 UI 调用的答案。不知道为什么它被否决了,但是如果您在 .NET 核心应用程序启动期间添加此提供程序,则此代码有效。