Using DataAnnotations and Localization in ASP.NET Core MVC

Using DataAnnotations and Localization in ASP.NET Core MVC

CheapASPNETHostingReview.com | Best and cheap ASP.NET Core MVC hosting. This article shows how ASP.NET Core localization can be used together with data annotations. The data annotations are used to decorate the data model, and when HTTP POST/PUT (also PATCH) Requests are sent with model errors, the error message is returned localized in the request culture.

Localization Setup

In the Startup class, the AddDataAnnotationsLocalization is added in the ConfigureServices method.

Now a model class can be created and the data annotations can be used. The Length property in this example has a range attribute, with an ErrorMessageResourceName and an ErrorMessageResourceType property set. The ErrorMessageResourceType is used to define the resource itself using the type and the ErrorMessageResourceName is used to define the resource identifier. Only the Length property has localized error messages implemented.

Now a MVC 6 controller can be created which uses the model class. This controller implements POST and PUT action methods, which uses the ModelState to validate the request. If the model is invalid, the error message is returned with a localized value.

Now the POST method can be called in Fiddler or Postman. Underneath is an example of a HTTP POST Request using the it-CH culture. The length property is outside the range and will return an model state error.

Localization can be used in data annotations like previous versions of MVC or Web API and provides a simple way of validating your data inputs.