Interpretation of ASP. NET 5 MVC6 Series Tutorials (15): MvcOptions Configuration

  • 2021-07-26 07:27:58
  • OfStack

Program model processing IApplicationModelConvention

In MvcOptions On the instance object of, there is 1 ApplicationModelConventions Attribute of type: List<IApplicationModelConvention> ), the property IApplicationModelConvention A collection of interfaces of type, which is used to process the application model ApplicationModel This collection is called when the MVC program starts, so we can modify or update it before calling. For example, we can define authorization in the database for all Controller and Action, read the data authorization information when the program starts, and then apply the model ApplicationModel To process. Examples are as follows:


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;

    //  According to the judgment condition, the operation is modified actionModel
   });

   //  According to the judgment condition, the operation is modified ControllerModel
  }
 }
}

Management of View Engine ViewEngines

In the instance object of MvcOptions, there is an ViewEngines attribute used to save the system's view engine collection, so that we can implement our own custom view engine. For example, in the chapter "Custom View View File Finding Logic", 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));
});

Input (InputFormater)/Output (OutputFormater) in Web API

Input

Web API and the current MVC input parameter processing, currently supports JSON and XML format, the specific processing classes are as follows:


JsonInputFormatter
XmlDataContractSerializerInputFormatter

Output

In Web API, there are four default output formatters:


HttpNoContentOutputFormatter
StringOutputFormatter
JsonOutputFormatter
XmlDataContractSerializerOutputFormatter

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

If it is an Action similar to the following, use HttpNoContentOutputFormatter Returns 204, which 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 it is the following method, it will also return a string, only the return type is string Action of the StringOutputFormatter Returns a string; If the return type is Action, use the JsonOutputFormatter Returns string data of type JSON.


public object GetData()
{
 return"The Data"; //  Return JSON
}

public string GetString()
{
 return"The Data"; //  Return string 
}

If neither of the above two types of Action is, the default is used JsonOutputFormatter Returns JSON data, if JsonOutputFormatter If the formatter is deleted by the following statement, it will be used XmlDataContractSerializerOutputFormatter Returns XML data.


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

Of course, you can also use ProducesAttribute Display declarations using JsonOutputFormatter ForMatter, as shown below.


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

Alternatively, you can use the base class Controller or use the ProducesAttribute Examples are as follows:


[Produces("application/json")]
public class JsonController : Controller { }

public class HomeController : JsonController
{
 public List<Data> GetMeData()
 {
  return GetDataFromSource();
 }
}

Of course, you can also declare the ProducesAttribute Examples are as follows:


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

Output Cache and Profile

In MVC6, the characteristics of OutputCache are determined by ResponseCacheAttribute Class, as shown below


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

The above example shows that the contents of the page are cached on the client for 100 seconds, in other words, 1 is added to the Response response header header Cache-Control Head and set the max-age=100 . The list of properties supported by this feature is as follows:

属性名称 描述
Duration 缓存时间,单位:秒,示例: CODE_TAG_REPLACE_MARK_20
NoStore true则设置 CODE_TAG_REPLACE_MARK_21
VaryByHeader 设置Vary header头
Location 缓存位置,如将Cache-Control设置为public, private或no-cache。

In addition, ResponseCacheAttribute Also supports 1 CacheProfileNam e property so that the globally set profile information configuration can be read for caching, as shown below:


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

Pass to MvcOptions Adj. CacheProfiles Add a value named MyProfile This configuration information can be used on all Action.

Other contents that we are already familiar with

We may already be familiar with the following contents, because they have been used in previous versions of MVC. These contents all exist as attributes of MvcOptions. The specific functions are listed as follows (not described in 11):

FiltersModelBindersModelValidatorProvidersValidationExcludeFiltersValueProviderFactories

The other two:
MaxModelValidationErrors
Set model validation to be the maximum number of errors displayed.

RespectBrowserAcceptHeader
Is the definition of Accept Header complied with when using the content contract functionality of Web API, by default when media type defaults to */* Accept header is ignored. If set to true, it is not ignored.


Related articles: