asp.net - 自定义模型绑定(bind)器未针对 ASP.NET Core 2 中的单个属性触发

标签 asp.net asp.net-core asp.net-core-2.0 asp.net-core-webapi custom-model-binder

我已经尝试过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/

    相关文章:

    asp.net - 合并 IdentityDbContext 和 DbContext ASP.NET MVC

    c# - 如何通过asp.net(访问数据库)OledbCommand获取输入(日期)并将其值插入到 "textbox"

    c# - 如何将 Json 格式化程序添加到 MvcCore?

    c# - DNX SDK版本 'dnx-clr-win-x86.1.0.0-beta8-15530'安装失败

    jquery - 当用户将鼠标悬停在 div 元素上时,如何在按钮上应用 jQuery 向下滑动?

    ASP.Net Core razor 页面处理程序成为一条包罗万象的路线

    centos - 如何在 CentOs 机器上安装 .net 核心?

    c# - 声明比角色更好吗

    angular - 将 IndentityServer4 与 Angular、AspNet Core 一起使用时,未找到签名 key 错误

    ASP.NET核心API : How to use MySQL