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

摘要:
PublicTaskDoSomethingAsync(){//Return Task}publicvoidDoSometing(){//Void method}publicstringGetString()}returnnull;//Return null}publicList<Data>GetData(){{returnnull;//returnnull}如果使用以下方法,则也会返回字符串。只有返回类型为string的操作才能使用StringOutputFormatter返回字符串;如果返回类型为object的Action,请使用JsonOutputFormatter返回JSON类型的字符串数据。PublicobjectGetData(){return“TheData”;//return JSON}publicstringGetString()}return“TheData”;//return string}如果上述两种类型的操作不同,则使用默认的JsonOutputFormatter返回JSON数据。如果通过以下语句删除JsonOutputFormatter晶格,则XmlDataContractSerializerOutputFormater将用于返回XML数据。服务。配置;当然,您也可以使用ProductionAttribute显示声明来使用JsonOutputFormatter格式器,如以下示例所示。此功能支持的属性列表
程序模型处理 IApplicationModelConvention

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

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视图文件查找逻辑》章节中,我们就利用了该特性,来实现了自己的自定义视图引擎,示例如下:

services.AddMvc().Configure<MvcOptions>(options =>
{
    options.ViewEngines.Clear();
    options.ViewEngines.Add(typeof(ThemeViewEngine));
});
Web API中的输入(InputFormater)/输出(OutputFormater)

输入

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

JsonInputFormatter
XmlDataContractSerializerInputFormatter

输出

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

HttpNoContentOutputFormatter
StringOutputFormatter
JsonOutputFormatter
XmlDataContractSerializerOutputFormatter

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

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

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类型的字符串数据。

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

public string GetString()
{
    return"The Data";  // 返回字符串
}

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

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

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

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

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

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

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

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

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

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

[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
NoStoretrue则设置Cache-Control:no-store
VaryByHeader设置Vary header头
Location缓存位置,如将Cache-Control设置为public, private或no-cache。

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

[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
            });
    });
}

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

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

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

  1. Filters
  2. ModelBinders
  3. ModelValidatorProviders
  4. ValidationExcludeFilters
  5. ValueProviderFactories

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

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

同步与推荐

本文已同步至目录索引:解读ASP.NET 5 & MVC6系列

免责声明:文章转载自《解读ASP.NET 5 &amp;amp; MVC6系列(15):MvcOptions配置》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇Ubuntu20.04在host-only模式下实现连接网络string中的CopyonWrite技术下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

随便看看

Linux snmp导入MIB库

Linux中使用的net-snmp带有一些标准MIB,但世界上有无数种支持snmp的设备,每个制造商都有自己的定义。这些定义不能包含在net-snmp附带的MIB中。因此,如果要正确轮询此类设备,必须加载制造商自己的MIB文件。...

PLSQL常用配置之窗口/版面保存、SQL格式化/美化、SQL注释去掉注释等快捷键配置、登陆历史修改配置

//Blog.csdn.net/eyeidolon/article/details/8251791 PLSQL常用配置的快捷键配置,如窗口/布局保存、SQL格式化/美化和SQL注释删除,以及登录历史修改1的配置。PL/SQLDeveloper记住登录密码当使用PL/SQLDeveloper时,默认情况下PL/SQLDeveloper会执行此窗口中的所有SQL...

Github仓库重命名

1.在Github上重命名仓库,转到您自己的仓库,找到Setting标记,然后单击Options中的Settings以设置Repositoryname。2.修改本地仓库信息。由于远程仓库名称已更改,因此本地对应的仓库名称也应更改。1.检查当前远程仓库的信息$gitremote-v列出了所有远程仓库信息,包括网站地址。2.修改本地对应远程仓库的地址。修改后,使...

Linux 安装.src.rpm源码包的方法

接下来是rpm安装过程。...

js 浏览器窗口 刷新、关闭事件

当前页面不会直接关闭,可以点击确定按钮关闭或刷新,也可以取消关闭或刷新。...

vue 获取元素高度

1、html2、JavaScript//获取高度值(内容高+padding+边框)letheight=this.$refs.getheight.offsetHeight;//获取元素样式值(存在单位)letheight=window.getComputedStyle(this.$refs.getheight).height;//获...