1. 程式人生 > >解讀ASP.NET 5 & MVC6系列(15):MvcOptions配置

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

程式模型處理 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
NoStore true則設定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,則不忽略。

同步與推薦