FormDataCollection 在 ASP.NET Core 2.1 中不起作用?
FormDataCollection not working in ASP.NET Core 2.1?
不要用 Core 1.1 或 2.0 检查它。
情况是在控制器方法中使用 FormDataCollection 作为参数时,如下所示:
[Route("[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
[Route("user")]
[HttpPost]
public HttpResponseMessage CheckUser(FormDataCollection form)
{
...
}
}
It returns 400 Bad Request 不管什么时候 Content-Type header.
但它适用于 .NET Framework 4.5:
[RoutePrefix("auth")]
public class AuthController : ApiController
{
[Route("user")]
[HttpPost]
public HttpResponseMessage user(FormDataCollection form)
{
...
}
}
当然可以Request.Form.TryGetValue(key, out var value)
。但是 class FormDataCollection 在 Core 中没有描述,我很好奇我们可以(并且应该)使用它来获取 post 参数吗?
FormDataCollection Microsoft.AspNetCore.Mvc.WebApiCompatShim 没有无参数构造函数,所以这就是问题的原因.根据 official documentation -
In order for binding to happen the class must have a public default
constructor and member to be bound must be public writable properties.
When model binding happens the class will only be instantiated using
the public default constructor, then the properties can be set.
不要用 Core 1.1 或 2.0 检查它。 情况是在控制器方法中使用 FormDataCollection 作为参数时,如下所示:
[Route("[controller]")]
[ApiController]
public class AuthController : ControllerBase
{
[Route("user")]
[HttpPost]
public HttpResponseMessage CheckUser(FormDataCollection form)
{
...
}
}
It returns 400 Bad Request 不管什么时候 Content-Type header.
但它适用于 .NET Framework 4.5:
[RoutePrefix("auth")]
public class AuthController : ApiController
{
[Route("user")]
[HttpPost]
public HttpResponseMessage user(FormDataCollection form)
{
...
}
}
当然可以Request.Form.TryGetValue(key, out var value)
。但是 class FormDataCollection 在 Core 中没有描述,我很好奇我们可以(并且应该)使用它来获取 post 参数吗?
FormDataCollection Microsoft.AspNetCore.Mvc.WebApiCompatShim 没有无参数构造函数,所以这就是问题的原因.根据 official documentation -
In order for binding to happen the class must have a public default constructor and member to be bound must be public writable properties. When model binding happens the class will only be instantiated using the public default constructor, then the properties can be set.