Introduction to ASP. NET 5 & MVC6 series tutorial (15): MvcOptions configuration, interpretation of ASP. NET
Program model processing IApplicationModelConvention
InMvcOptions
There isApplicationModelConventions
Attribute (type:List<IApplicationModelConvention>
).IApplicationModelConvention
Interface set for processing the application modelApplicationModel
The 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:
UseHttpNoContentOutputFormatter
204 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 isstring
To useStringOutputFormatter
Returns a string. If the return type is the Action of the object,JsonOutputFormatter
Returns 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 usedJsonOutputFormatter
Returns JSON data. IfJsonOutputFormatter
The formatter is deleted using the following statement.XmlDataContractSerializerOutputFormatter
Returns XML data.
services.Configure<MvcOptions>(options => options.OutputFormatters.RemoveAll(formatter => formatter.Instance is JsonOutputFormatter));
You can also useProducesAttribute
Display declaration usageJsonOutputFormatter
The 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:ResponseCacheAttribute
For 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-Control
Header, 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,ResponseCacheAttribute
ACacheProfileNam
E 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 }); });}
ForwardMvcOptions
OfCacheProfiles
Add a property nameMyProfile
The 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.