开发者

AllowHtml, HttpRequestValidationException and ModelState

开发者 https://www.devze.com 2023-03-21 06:10 出处:网络
I have this viewmodel public class FooBarViewModel { public string Foo { get; set; } [AllowH开发者_如何学Ctml]

I have this viewmodel

public class FooBarViewModel
{
    public string Foo { get; set; }

    [AllowH开发者_如何学Ctml]
    public string Bar { get; set; }
}

Instead of throwing a HttpRequestValidationException if .Foo is submitted with html in it, I want to add a message to ModelState. How could I do that?


You could decorate the Foo property with the [AllowHtml] attribute as well and inside the controller check whether it contains HTML which would allow you to add a custom error to the model state.


The exception will be thrown within the DefaultModelBinder at the point where it calls ValueProvider.GetValue.

To change the behaviour to catch the exception and convert it into a ModelState error you would need to extend or replace the DefaultModelBinder.

One possibility is to override BindModel, and at the point where it calls GetValue:

ValueProviderResult valueProviderResult = bindingContext.UnvalidatedValueProvider.GetValue(bindingContext.ModelName, skipValidation: !performRequestValidation);

try and catch the exceptions and call bindingContext.ModelState.AddModelError.

The problem is that the DefaultModelBinder is quite complex so you may need to think carefully about how such a change needs to interact with the rest of the model binding ecosystem.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号