好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

解读ASP.NET 5 & MVC6系列教程(15):MvcOptions配置

程序模型处理 IApplicationModelConvention

在 MvcOptions 的实例对象上,有一个 ApplicationModelConventions 属性(类型是: List<IApplicationModelConvention> ),该属性 IApplicationModelConvention 类型的接口集合,用于处理应用模型 ApplicationModel ,该集合是在MVC程序启动的时候进行调用,所以在调用之前,我们可以对其进行修改或更新,比如,我们可以针对所有的Controller和Action在数据库中进行授权定义,在程序启动的时候读取数据授权信息,然后对应用模型 ApplicationModel 进行处理。 示例如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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;

 

     // 根据判断条件,操作修改actionModel

    });

 

    // 根据判断条件,操作修改ControllerModel

   }

  }

}

视图引擎的管理ViewEngines

在MvcOptions的实例对象中,有一个ViewEngines属性用于保存系统的视图引擎集合,以便可以让我们实现自己的自定义视图引擎,比如在《自定义View视图文件查找逻辑》章节中,我们就利用了该特性,来实现了自己的自定义视图引擎,示例如下:

?

1

2

3

4

5

services.AddMvc().Configure<MvcOptions>(options =>

{

  options.ViewEngines.Clear();

  options.ViewEngines.Add( typeof (ThemeViewEngine));

});

Web API中的输入(InputFormater)/输出(OutputFormater)

输入

Web API和目前的MVC的输入参数的处理,目前支持JSON和XML格式,具体的处理类分别如下:

?

1

2

JsonInputFormatter

XmlDataContractSerializerInputFormatter

输出

在Web API中,默认的输出格式化器有如下四种:

?

1

2

3

4

HttpNoContentOutputFormatter

StringOutputFormatter

JsonOutputFormatter

XmlDataContractSerializerOutputFormatter

上述四种在系统中,是根据不同的情形自动进行判断输出的,具体判断规则如下:

如果是如下类似的Action,则使用 HttpNoContentOutputFormatter 返回204,即NoContent。

 

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

public Task DoSomethingAsync()

{

  // 返回Task

}

 

public void DoSomething()

{

  // Void方法

}

 

public string GetString()

{

  return null ; // 返回null

}

 

public List<Data> GetData()

{

  return null ; // 返回null

}

如果是如下方法,同样是返回字符串,只有返回类型是 string 的Action,才使用 StringOutputFormatter 返回字符串;返回类型是object的Action,则使用 JsonOutputFormatter 返回JSON类型的字符串数据。

?

1

2

3

4

5

6

7

8

9

public object GetData()

{

  return "The Data" ; // 返回JSON

}

 

public string GetString()

{

  return "The Data" ; // 返回字符串

}

如果上述两种类型的Action都不是,则默认使用 JsonOutputFormatter 返回JSON数据,如果 JsonOutputFormatter 格式化器通过如下语句被删除了,那就会使用 XmlDataContractSerializerOutputFormatter 返回XML数据。

?

1

2

3

services.Configure<MvcOptions>(options =>

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

);

当然,你也可以使用 ProducesAttribute 显示声明使用 JsonOutputFormatter 格式化器,示例如下。

?

1

2

3

4

5

6

7

8

9

public class Product2Controller : Controller

{

  [Produces( "application/json" )]

  //[Produces("application/xml")]

  public Product Detail( int id)

  {

   return new Product() { ProductId = id, ProductName = "商品名称" };

  }

}

或者,可以在基类Controller上,也可以使用 ProducesAttribute ,示例如下:

?

1

2

3

4

5

6

7

8

9

10

[Produces( "application/json" )]

public class JsonController : Controller { }

 

public class HomeController : JsonController

{

  public List<Data> GetMeData()

  {

   return GetDataFromSource();

  }

}

当然,也可以在全局范围内声明该 ProducesAttribute ,示例如下:

?

1

2

3

services.Configure<MvcOptions>(options =>

  options.Filters.Add(newProducesAttribute( "application/json" ))

);

Output Cache 与 Profile

在MVC6中,OutputCache的特性由 ResponseCacheAttribute 类来支持,示例如下:

?

1

2

3

4

5

[ResponseCache(Duration = 100)]

public IActionResult Index()

{

  return Content(DateTime.Now.ToString());

}

上述示例表示,将该页面的内容在客户端缓存100秒,换句话说,就是在Response响应头header里添加一个 Cache-Control 头,并设置 max-age=100 。 该特性支持的属性列表如下:

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

另外, ResponseCacheAttribute 还支持一个 CacheProfileNam e属性,以便可以读取全局设置的profile信息配置,进行缓存,示例如下:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

[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

    });

  });

}

通过向 MvcOptions 的 CacheProfiles 属性值添加一个名为 MyProfile 的个性设置,可以在所有的Action上都使用该配置信息。

其它我们已经很熟悉的内容

以下内容我们可能都已经非常熟悉了,因为在之前的MVC版本中都已经使用过了,这些内容均作为MvcOptions的属性而存在,具体功能列表如下(就不一一叙述了):

FiltersModelBindersModelValidatorProvidersValidationExcludeFiltersValueProviderFactories

另外两个:
MaxModelValidationErrors
置模型验证是显示的最大错误数量。

RespectBrowserAcceptHeader
在使用Web API的内容协定功能时,是否遵守Accept Header的定义,默认情况下当media type默认是 */* 的时候是忽略Accept header的。如果设置为true,则不忽略。

查看更多关于解读ASP.NET 5 & MVC6系列教程(15):MvcOptions配置的详细内容...

  阅读:61次