Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Filter to execute before model validation

I have a filter that sets the CurrentUICulture of the current thread to be a value pulled from a cookie

And I have a model that is being validated using the FluentValidation library

[Validator(typeof(MyInputModelValidator))]
public class MyInputModel


public class MyInputModelValidator: AbstractValidator<MyInputModel>
    {
        public MyInputModelValidator()
        {
            var x = Thread.CurrentThread.CurrentUICulture.Name;
            RuleFor(o => o.Country).NotEmpty().WithMessage(Resources.NoCountryError);

I want the thread culture to be changed by this point so it pulls the correct language for the error message

If I put a break point on the validator above I can see the thread has the wrong culture.

If I run the code further, it then hits a break point on the filter which changes the culture of the thread

How can I make the filter code run before the model validation kicks in

I have tried both decorating the controller action method with the filter attribute and applying it globally e.g.

GlobalConfiguration.Configuration.Filters.Add(new LocalizationApiFilter());

this is web api, not mvc , though the concepts are the same

any ideas?

like image 646
ChrisCa Avatar asked Oct 17 '13 18:10

ChrisCa


1 Answers

How can I make the filter code run before the model validation kicks in

I think this is not possible. Model binding happens before the action filters run in the pipeline. ASP.NET Web API pipeline is something that can be extended but not modified. You can workaround this situation by using something other than a filter to set the culture, say a message handler. Authorization filters also run before model binding but an authorization filter is for authorization and probably not a good fit for this.

like image 59
Badri Avatar answered Oct 21 '22 12:10

Badri