Introduction to ASP. NET 5 & MVC6 series tutorial (15): MvcOptions configuration, interpretation of ASP. NET

Source: Internet
Author: User

Introduction to ASP. NET 5 & MVC6 series tutorial (15): MvcOptions configuration, interpretation of ASP. NET

Program model processing IApplicationModelConvention

InMvcOptionsThere isApplicationModelConventionsAttribute (type:List<IApplicationModelConvention>).IApplicationModelConventionInterface set for processing the application modelApplicationModelThe set is called when the MVC program is started, so we can modify or update it before calling, for example, we can define authorization for all controllers and actions in the database, read data authorization information when the program starts, and then apply the ModelApplicationModel. Example:

Public class PermissionCheckApplicationModelConvention: IApplicationModelConvention {public void Apply (ApplicationModel application) {foreach (var controllerModel in application. controllers) {var controllerType = controllerModel. controllerType; var controllerName = controllerModel. controllerName; controllerModel. actions. toList (). forEach (actionModel => {var actionName = actionModel. actionName; var parameters = actionModel. parameters; // modify the actionModel according to the Judgment condition}); // modify the ControllerModel according to the Judgment condition }}}

View engine management ViewEngines

In the MvcOptions instance object, there is a ViewEngines attribute used to save the view engine set of the system, so that we can implement our own custom view engine, for example, in the "search logic for custom View files" section, we use this feature to implement our own custom View engine. The example is as follows:

services.AddMvc().Configure<MvcOptions>(options =>{ options.ViewEngines.Clear(); options.ViewEngines.Add(typeof(ThemeViewEngine));});

InputFormater/OutputFormater in Web APIs)

Input

Processing of Web APIs and input parameters of MVC currently supports JSON and XML formats. The specific processing classes are as follows:

JsonInputFormatterXmlDataContractSerializerInputFormatter

Output

In Web APIs, the default output formatter has the following four types:

HttpNoContentOutputFormatterStringOutputFormatterJsonOutputFormatterXmlDataContractSerializerOutputFormatter

The above four types of outputs are automatically judged based on different situations in the system. The specific judgment rules are as follows:

UseHttpNoContentOutputFormatter204 is returned, that is, NoContent.

Public Task DoSomethingAsync () {// return Task} public void DoSomething () {// Void method} public string GetString () {return null; // return null} public List <Data> GetData () {return null; // return null}

If the method is as follows, it is also a return string, only the return type isstringTo useStringOutputFormatterReturns a string. If the return type is the Action of the object,JsonOutputFormatterReturns string data of the JSON type.

Public object GetData () {return "The Data"; // return JSON} public string GetString () {return "The Data"; // return string}

If neither of the above two types of actions is usedJsonOutputFormatterReturns JSON data. IfJsonOutputFormatterThe formatter is deleted using the following statement.XmlDataContractSerializerOutputFormatterReturns XML data.

services.Configure<MvcOptions>(options => options.OutputFormatters.RemoveAll(formatter => formatter.Instance is JsonOutputFormatter));

You can also useProducesAttributeDisplay declaration usageJsonOutputFormatterThe following is an example.

Public class Product2Controller: Controller {[Produces ("application/json")] // [Produces ("application/xml")] public Product Detail (int id) {return new Product () {ProductId = id, ProductName = "Product Name "};}}

Alternatively, you can useProducesAttribute, For example:

[Produces("application/json")]public class JsonController : Controller { }public class HomeController : JsonController{ public List<Data> GetMeData() {  return GetDataFromSource(); }}

Of course, you can also declareProducesAttribute, For example:

services.Configure<MvcOptions>(options => options.Filters.Add(newProducesAttribute("application/json")));

Output Cache and Profile

In MVC6, the features of OutputCache are as follows:ResponseCacheAttributeFor example:

[ResponseCache(Duration = 100)]public IActionResult Index(){ return Content(DateTime.Now.ToString());}

The preceding example indicates that the content of the page is cached on the client for 100 seconds. In other words, addCache-ControlHeader, and setmax-age=100. This feature supports the following attributes:

Attribute name Description
Duration Cache Time, in seconds, for example:Cache-Control:max-age=100
NoStore TrueCache-Control:no-store
VaryByHeader Set Vary header
Location Cache location, for example, set cache-Control to public, private, or no-Cache.

In addition,ResponseCacheAttributeACacheProfileNamE attribute, so that you can read the profile configuration of the global settings and cache it, for example:

[ResponseCache(CacheProfileName = "MyProfile")]public IActionResult Index(){ return Content(DateTime.Now.ToString());}public void ConfigureServices(IServiceCollection services){ services.Configure<MvcOptions>(options => {  options.CacheProfiles.Add("MyProfile",   new CacheProfile   {    Duration = 100   }); });}

ForwardMvcOptionsOfCacheProfilesAdd a property nameMyProfileThe configuration information can be used in all actions.

Other content that we are already familiar

We may be very familiar with the following content, because it has been used in previous MVC versions, and these contents exist as the attributes of MvcOptions, the specific functions are as follows (not described in detail ):

FiltersModelBindersModelValidatorProvidersValidationExcludeFiltersValueProviderFactories

The other two are:
MaxModelValidationErrors
Set Model verification to the maximum number of errors displayed.

RespectBrowserAcceptHeader
Whether to comply with the Accept Header definition when using the content Agreement function of Web APIs. By default, when media type is*/*The Accept header is ignored. If this parameter is set to true, this parameter is not ignored.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.