title
stringlengths
3
46
content
stringlengths
0
1.6k
17:791
17:792
This ensures maximum independence of functionalities and simpler code. For instance, once the authorization and authentication modules are active, no other module needs to worry about authorization anymore. Each piece controller code can focus on application-specific business stuff.
17:793
Server-side and client-side validation
17:794
Validation logic has been completely factored out from the application code and has been confined to the definition of validation attributes. The developer just needs to specify the validation rule to apply to each model property, by decorating the property with an adequate validation attribute.
17:795
Validation rules are checked automatically when action method parameters are instantiated. Both errors and paths in the model (where they occurred) are then recorded in a dictionary that is contained in the ModelState controller property. The developer has the responsibility for verifying whether there are errors by checking ModelState.IsValid, in which case the developer must return the same ViewModel to the same view so that the user can correct any errors.
17:796
Error messages are automatically shown in the view, with no action required from the developer. The developer is only required to do the following:
17:797
17:798
Add span or div with an asp-validation-for attribute next to each input field, which will be automatically filled with the possible error.
17:799
Add div with an asp-validation-summary attribute that will be automatically filled with the validation error summary. See the Using Razor tag helpers section for more details.
17:800
17:801
It is sufficient to add some JavaScript references by invoking the _ValidationScriptsPartial.cshtml view with the partial tag, enabling the same validation rules on the client side so that errors are shown to the user before the form is posted to the server. Some predefined validation attributes are contained in the S stem.ComponentModel.DataAnnotations and Microsoft.AspNetCore.Mvc namespaces and include the following attributes:
17:802
17:803
The Required attribute requires the user to specify a value for the property that it decorates. An implicit Required attribute is automatically applied to all non-nullable properties, such as all floats, integers, and decimals, since they can’t have a null value.
17:804
The Range attribute constrains numeric quantities within a range.
17:805
They also include attributes that constrain string lengths.
17:806
17:807
Custom error messages can be inserted directly into the attributes, or attributes can refer to the property of the resource types containing them.
17:808
The developer can define their custom attributes by providing the validation code, both in C# and in JavaScript for client-side validation. The definition of custom validation attributes is discussed in this article: https://blogs.msdn.microsoft.com/mvpawardprogram/2017/01/03/asp-net-core-mvc/.
17:809
Attribute-based validation can be replaced by other validation providers, such as the FluentValidation library that defines validation rules for each type using a fluent interface. It is enough to change a provider in a collection contained in the MVC options object. This can be configured through an action passed to the builder.Services.AddControllersWithViews method.
17:810
MVC options can be configured as follows:
17:811
builder.Services.AddControllersWithViews(o => {
17:812
...
17:813
// code that modifies o properties
17:814
});
17:815
17:816
The validation framework automatically checks whether numeric and date inputs are well formatted according to the selected culture.
17:817
ASP.NET Core globalization
17:818
In multicultural applications, pages must be served according to the language and cultural preferences of each user. Typically, multicultural applications can serve their content in a few languages, and they can handle dates and numeric formats in several more languages. In fact, while the content in all supported languages must be produced manually, .NET has the native capability of formatting and parsing dates and numbers in all cultures.
17:819
For instance, a web application might not support unique content for all English-based cultures (en), but it might support all known English-based cultures regarding number and date formats (en-US, en-GB, en-CA, and so on).
17:820
The culture used for numbers and dates in a .NET thread is contained in the Thread.CurrentThread.CurrentCulture property. Hence, by setting this property to new CultureInfo(`en-CA`), numbers and dates will be formatted/parsed according to the Canadian format. Thread.CurrentThread.CurrentUICulture, instead, decides on the culture of the resource files; that is, it selects a culture-specific version of each resource file or view. Accordingly, a multicultural application is required to set the two cultures associated with the request thread and organize multilingual content into language-dependent resource files and/or views.
17:821
According to the Separation of Concerns principle, the whole logic used to set the request culture according to the user’s preferences is factored out into a specific module of the ASP.NET Core pipeline. To configure this module, as a first step, we set the supported date/number cultures, as shown in the following example:
17:822
var supportedCultures = new[]
17:823
{
17:824
new CultureInfo(`en-AU`),
17:825
new CultureInfo(`en-GB`),
17:826
new CultureInfo(`en`),
17:827
new CultureInfo(`es-MX`),
17:828
new CultureInfo(`es`),
17:829
new CultureInfo(`fr-CA`),
17:830
new CultureInfo(`fr`),
17:831
new CultureInfo(`it-CH`),
17:832
new CultureInfo(`it`)
17:833
};
17:834
17:835
Then, we set the languages supported for the content. Usually, a version of the language that is not specific to any country is selected to keep the number of translations small enough, as shown here:
17:836
var supportedUICultures = new[]
17:837
{
17:838
new CultureInfo(`en`),
17:839
new CultureInfo(`es`),
17:840
new CultureInfo(`fr`),
17:841
new CultureInfo(`it`)
17:842
};
17:843
17:844
Then, we add the culture middleware to the pipeline, as shown here:
17:845
app.UseRequestLocalization(new RequestLocalizationOptions
17:846
{
17:847
DefaultRequestCulture = new RequestCulture(`en`, `en`),
17:848
// Formatting numbers, dates, etc.
17:849
SupportedCultures = supportedCultures,
17:850
// UI strings that we have localized.
17:851
SupportedUICultures = supportedUICultures,
17:852
FallBackToParentCultures = true,
17:853
FallBackToParentUICultures = true
17:854
});
17:855
17:856
If the culture requested by the user is explicitly found among the ones listed in supportedCultures or supportedUICultures, it is used without modifications. Otherwise, since FallBackToParentCultures and FallBackToParentUICultures are true, the parent culture is tried; that is, for instance, if the required fr-FR culture is not found among those listed, then the framework searches for its generic version, fr. If this attempt also fails, the framework uses the cultures specified in DefaultRequestCulture.
17:857
By default, the culture middleware searches the culture selected for the current user, with three providers that are tried in the order shown here:
17:858
17:859
The middleware looks for the culture and ui-culture query string parameters.
17:860
If the previous step fails, the middleware looks for a cookie named .AspNetCore.Culture, the value of which is expected to be as in this example: c=en-US|uic=en.
17:861
If both previous steps fail, the middleware looks for the Accept-Language request header sent by the browser, which can be changed in the browser settings, and which is initially set to the operating system culture.
17:862
17:863
With the preceding strategy, the first time a user requests an application page, the browser culture is taken (the provider listed in step 3). Then, if the user clicks a language-change link with the right query string parameters, a new culture is selected by provider 1. Usually, once a language link has been clicked, the server also generates a language cookie to remember the user’s choice through provider 2.
17:864
The simplest way to provide content localization is to provide a different view for each language. Hence, if we would like to localize the Home.cshtml view for different languages, we must provide views named Home.en.cshtml, Home.es.cshtml, and so on. If no view specific to the ui-culture thread is found, the non-localized Home.cshtml version of the view is chosen.
17:865
View localization must be enabled by calling the AddViewLocalization method, as shown here:
17:866
builder.Services.AddControllersWithViews()
17:867
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
17:868
17:869
Another option is to store simple strings or HTML fragments in resource files specific to all supported languages. The usage of resource files must be enabled by calling the AddLocalization method in the configure services section, as shown here:
17:870
builder.Services.AddLocalization(options =>
17:871
options.ResourcesPath = `Resources`);
17:872
17:873
ResourcesPath is the root folder where all resource files will be placed. If it is not specified, an empty string is assumed, and the resource files will be placed in the web application root. Resource files for a specific view (say, the /Views/Home/Index.cshtml view) must have a path like this:
17:874
<ResourcesPath >/Views/Home/Index.<culture name>.resx
17:875
17:876
Hence, if ResourcesPath is empty, resources must have the /Views/Home/Index.<culture name>.resx path; that is, they must be placed in the same folder as the view.
17:877
Once the key-value pairs for all the resource files associated with a view have been added, localized HTML fragments can be added to the view, as follows:
17:878
17:879
Inject IViewLocalizer into the view with @inject IViewLocalizer Localizer
17:880
Where needed, replace the text in the View with access to the Localizer dictionary, such as Localizer[“myKey”], where “myKey” is a key used in the resource files.
17:881
17:882
The following code shows an example of the IViewLocalizer dictionary:
17:883
@{
17:884
ViewData[`Title`] = Localizer[`HomePageTitle`];
17:885
}
17:886
<h2>@ViewData[`MyTitle`]</h2>
17:887
17:888
If localization fails because the key is not found in the resource file, the key itself is returned. Strings used in data annotation, such as validation attributes, are used as keys in resource files if data annotation localization is enabled, as shown here:
17:889
builder.Services.AddControllersWithViews()
17:890
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)