我已经尝试过this ,但我不认为这是我的情况。 This也不行。
我正在使用 ASP.NET Core 2 Web API。我刚刚创建了一个虚拟模型绑定(bind)器(现在它的作用无关紧要):
public class SanitizeModelBinder : IModelBinder
{
public Task BindModelAsync(ModelBindingContext bindingContext)
{
if (bindingContext == null)
{
throw new ArgumentNullException(nameof(bindingContext));
}
var modelName = bindingContext.ModelName;
return Task.CompletedTask;
}
}
现在,我有一个模型。这个:
public class UserRegistrationInfo
{
public string Email { get; set; }
[ModelBinder(BinderType = typeof(SanitizeModelBinder))]
public string Password { get; set; }
}
和一个 Action 方法:
[AllowAnonymous]
[HttpPost("register")]
public async Task<IActionResult> RegisterAsync([FromBody] UserRegistrationInfo registrationInfo)
{
var validationResult = validateEmailPassword(registrationInfo.Email, registrationInfo.Password);
if (validationResult != null)
{
return validationResult;
}
var user = await _authenticationService.RegisterAsync(registrationInfo.Email, registrationInfo.Password);
if (user == null)
{
return StatusCode(StatusCodes.Status500InternalServerError, "Couldn't save the user.");
}
else
{
return Ok(user);
}
}
如果我从客户端发出 post 请求,我的自定义模型绑定(bind)器不会被触发,并且在 action 方法中继续执行。
我尝试过的事情:
申请
ModelBinder
属性到整个模型对象:[ModelBinder(BinderType = typeof(SanitizeModelBinder))]
public class UserRegistrationInfo
{
public string Email { get; set; }
public string Password { get; set; }
}
这有效,但对于整个对象,我不希望那样。我希望默认模型绑定(bind)器完成其工作,然后将我的自定义模型绑定(bind)器仅应用于某些属性。
我读了here那是
FromBody
的错,所以我把它从 action 方法中删除了。它也不起作用。我试图更改属性
ModelBinder
对于 BindProperty
这里:public class UserRegistrationInfo
{
public string Email { get; set; }
[BindProperty(BinderType = typeof(SanitizeModelBinder))]
public string Password { get; set; }
}
但它不起作用。
令人失望的是,原本应该简单的事情变得非常繁琐,分散在几个博客和 github 问题上的信息根本没有帮助。所以,如果你能帮助我,我将不胜感激。
最佳答案
对于 ModelBinder
, 你需要使用 application/x-www-form-urlencoded
在客户端和[FromForm]
在服务器端。
对于 ApiController
,它的默认绑定(bind)是JsonConverter
.
请按照以下步骤操作:
[AllowAnonymous]
[HttpPost("register")]
public async Task<IActionResult> RegisterAsync([FromForm]UserRegistrationInfo registrationInfo)
{
return Ok(registrationInfo);
}
post(url: string, model: any): Observable <any> {
let formData: FormData = new FormData();
formData.append('id', model.id);
formData.append('applicationName', model.applicationName);
return this._http.post(url, formData)
.map((response: Response) => {
return response;
}).catch(this.handleError);
}
使用
json
使用自定义绑定(bind),您可以自定义格式化程序,并引用 Custom formatters in ASP.NET Core Web API
关于asp.net - 自定义模型绑定(bind)器未针对 ASP.NET Core 2 中的单个属性触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55669289/