自定义模型绑定器不为ASP.NET Core 2中的单个属性激发 [英] Custom model binder not firing for a single property in ASP.NET Core 2

查看:0
本文介绍了自定义模型绑定器不为ASP.NET Core 2中的单个属性激发的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经尝试了this,但我认为这不是我的情况。This也不起作用。

我使用的是ASP.NET Core 2 Web API。我刚刚创建了一个虚拟模型活页夹(现在它的作用并不重要):

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

和操作方法:

[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请求,则不会激发我的自定义模型绑定器,并且在操作方法中继续执行。

我已尝试的内容:

ModelBinder属性应用于整个模型对象:

[ModelBinder(BinderType = typeof(SanitizeModelBinder))]
public class UserRegistrationInfo
{
    public string Email { get; set; }
    public string Password { get; set; }
}

这是有效的,但对于整个对象,我不希望这样。我希望默认模型绑定器完成其工作,然后将我的自定义模型绑定器仅应用于某些属性。

我读到hereFromBody的错误,所以我将其从操作方法中删除。它也不起作用。

我尝试在以下位置更改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,默认绑定为JsonConverter

按照以下步骤操作:

  1. 更改操作

    [AllowAnonymous]
    [HttpPost("register")]
    public async Task<IActionResult> RegisterAsync([FromForm]UserRegistrationInfo registrationInfo)
    {
        return Ok(registrationInfo);
    }
    
  2. 角度

    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与自定义绑定一起使用,您可以自定义格式化程序,并参考Custom formatters in ASP.NET Core Web API

这篇关于自定义模型绑定器不为ASP.NET Core 2中的单个属性激发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆