Interpreting ASP.NET 5 & MVC6 Series (15): MvcOptions Configuration

Interpreting ASP.NET 5 & MVC6 Series (15): MvcOptions Configuration

Program model handling IApplicationModelConvention

On the instance object of MvcOptions, there is an ApplicationModelConventions property (type: List ), the interface collection of the property IApplicationModelConvention type is used to process the application model ApplicationModel. This collection is called when the MVC program starts, so before calling it, we can modify or update it. For example, we can define authorization for all Controllers and Actions in the database, read the data authorization information when the program starts, and then process the application model ApplicationModel. The example is as follows:

  1. public   class PermissionCheckApplicationModelConvention : IApplicationModelConvention
  2. {
  3. public   void Apply(ApplicationModel application)
  4. {
  5. foreach (var controllerModel in application.Controllers)
  6. {
  7. var controllerType = controllerModel.ControllerType;
  8. var controllerName = controllerModel.ControllerName;
  9.  
  10. controllerModel.Actions.ToList().ForEach(actionModel =>
  11. {
  12. var actionName = actionModel.ActionName;
  13. var parameters = actionModel.Parameters;
  14.  
  15. //According to the judgment conditions, modify the actionModel  
  16. });
  17.  
  18. //According to the judgment conditions, modify the ControllerModel  
  19. }
  20. }
  21. }

View Engine ManagementViewEngines

In the instance object of MvcOptions, there is a ViewEngines property that is used to save the system's view engine collection so that we can implement our own custom view engine. For example, in the "Custom View View File Search Logic" chapter, we used this feature to implement our own custom view engine. The example is as follows:

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

InputFormater/OutputFormater in Web API

enter

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

  1. JsonInputFormatter
  2. XmlDataContractSerializerInputFormatter

Output

In Web API, there are four default output formatters:

  1. HttpNoContentOutputFormatter
  2. StringOutputFormatter
  3. JsonOutputFormatter
  4. XmlDataContractSerializerOutputFormatter

The above four types are automatically judged and output according to different situations in the system. The specific judgment rules are as follows:

If the action is similar to the following, use HttpNoContentOutputFormatter to return 204, which means NoContent.

  1. public Task DoSomethingAsync()
  2. {
  3. // Return Task  
  4. }
  5.  
  6. public   void DoSomething()
  7. {
  8. // Void method  
  9. }
  10.  
  11. public string GetString()
  12. {
  13. return   null ; // returns null  
  14. }
  15.  
  16. public List GetData() { return   null ; // returns null }

If the following method also returns a string, only the Action whose return type is string will use StringOutputFormatter to return the string; if the Action whose return type is object, use JsonOutputFormatter to return the string data of JSON type.

  1. public object GetData()
  2. {
  3. return "The Data" ; // Return JSON  
  4. }
  5.  
  6. public string GetString()
  7. {
  8. return "The Data" ; // Return a string  
  9. }

If neither of the above two types of actions is used, JsonOutputFormatter is used by default to return JSON data. If the JsonOutputFormatter formatter is deleted through the following statement, XmlDataContractSerializerOutputFormatter will be used to return XML data.

  1. services.Configure(options => options.OutputFormatters.RemoveAll(formatter => formatter.Instance is JsonOutputFormatter) )

Of course, you can also use ProducesAttribute to explicitly declare the use of the JsonOutputFormatter formatter, as shown below.

  1. public   class Product2Controller : Controller
  2. {
  3. [Produces( "application/json" )]
  4. //[Produces("application/xml")]  
  5. public ProductDetail( int id)
  6. {
  7. return   new Product() { ProductId = id, ProductName = "Product Name" };
  8. }
  9. }

Alternatively, you can use the ProducesAttribute on the base Controller class, as shown below:

  1. [Produces( "application/json" )]
  2. public   class JsonController : Controller { }
  3.  
  4. public   class HomeController : JsonController
  5. {
  6. public List GetMeData() { return GetDataFromSource(); } }

Of course, you can also declare the ProducesAttribute in the global scope, as shown below:

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

Output Cache and Profile

In MVC6, the OutputCache feature is supported by the ResponseCacheAttribute class, as shown below:

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

The above example indicates that the content of the page will be cached on the client for 100 seconds. In other words, a Cache-Control header is added to the Response header and max-age=100 is set. The following are the attributes supported by this feature:

In addition, ResponseCacheAttribute also supports a CacheProfileName attribute so that the globally set profile information configuration can be read for caching. The example is as follows:

  1. [ResponseCache(CacheProfileName = "MyProfile" )]
  2. public IActionResult Index()
  3. {
  4. return Content(DateTime.Now.ToString());
  5. }
  6.  
  7. public   void ConfigureServices(IServiceCollection services)
  8. {
  9. services.Configure(options => { options.CacheProfiles.Add( "MyProfile" , new CacheProfile { Duration = 100 }); }); }
  10.  
  11.   

By adding a personality setting named MyProfile to the CacheProfiles property value of MvcOptions, you can use this configuration information on all Actions.

Other things we are already familiar with

We may be very familiar with the following content because we have used it in previous MVC versions. These contents exist as properties of MvcOptions. The specific function list is as follows (I will not describe them one by one):

1.Filters

2. ModelBinders

3.ModelValidatorProviders

4.ValidationExcludeFilters

5.ValueProviderFactories

Two more:

MaxModelValidationErrors

Set model validation to display the highest number of errors.

RespectBrowserAcceptHeader

When using the content agreement function of Web API, whether to comply with the definition of Accept Header. By default, when the media type is */*, the Accept header is ignored. If set to true, it is not ignored.

<<:  Interpreting ASP.NET 5 & MVC6 Series (14): View Component

>>:  Interpreting ASP.NET 5 & MVC6 Series (16): Customizing View View File Search Logic

Recommend

How did Chinese tea conquer the world?

No matter what time Have a cup of tea first Whene...

What kind of plant is Stephania? Is it true that cephalothin can treat COVID-19?

Recently, Qianjinteng suddenly became popular bec...

Gurgle, gurgle! Why is there always gas in my stomach?

This article was reviewed by Dr. Tao Ning, Associ...

E-commerce promotion and paid membership operation strategies!

The last e-commerce festival of this year, "...

BMW 7 Series flagship model priced over $150,000 announced

Recently, BMW officially announced the price of t...

Mobile phone flight mode liberation: these apps are waiting to benefit

Once upon a time, beautiful stewardesses would re...

A collection of advertising creation tips that took 8 years to compile

I also summarized 12 of my own advertising creati...

Is it so easy to make your own wine? Be careful, beware of methanol poisoning...

Grape wine in luminous cup, a glass of homemade w...