MVC5和MVC6的區別
在MVC5的時候,web.config文件無疑是整個配置的核心,從web配置,到應用程序的參數,都可以寫在web.config里面的。
一個典型的web.config看上去是這樣的。應用程序使用的各種設定,項目中的各種動態鏈接庫及其版本信息,錯誤頁面的指定,未知文件擴展名的注冊等等,包羅萬象。
<?xml version="1.0" encoding="utf-8"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=301880
-->
<configuration>
<appSettings>
<add key="webpages:Version" value="3.0.0.0" />
<add key="webpages:Enabled" value="false" />
<add key="ClientValidationEnabled" value="true" />
<add key="UnobtrusiveJavaScriptEnabled" value="true" />
<add key="URLBASE" value="http://codesnippet.info" />
<add key="DEBUGMODE" value="true" />
<!--<add key="DEBUGMODE" value="false" />-->
<!-- Image-->
<!--<add key="Image" value="Mongo" />-->
<add key="Image" value="FileSystem" />
<!--<add key="Image" value="QiNiu" />-->
<!-- Thumbnail -->
<!--<add key="Thumbnail" value="Mongo" />-->
<add key="Thumbnail" value="FileSystem" />
<!--<add key="Thumbnail" value="QiNiu" />-->
<!-- Github OAuth -->
<add key="GITHUB:ClientSecret" value="123456" />
<add key="GITHUB:ClientID" value="123456" />
<add key="GITHUB:AppName" value="codesnippet" />
<!-- QQ OAuth-->
<add key="QQ:AppID" value="123456" />
<add key="QQ:AppKey" value="123456"/>
<add key="QQ:CallBack" value="http://www.codesnippet.info/Home/QQOAuth"/>
<add key="QQ:AuthorizeURL" value="https://graph.qq.com/oauth2.0/authorize" />
<!-- QiNiu Storage -->
<add key="QINIU:AK" value="123456" />
<add key="QINIU:SK" value="123456" />
<add key="QINIU:BUCKET" value="gridfilesystem" />
<add key="QINIU:URLBASE" value="123456" />
<!-- Search Method -->
<!--<add key="SearchMethod" value="MongoTextSearch" />-->
<add key="SearchMethod" value="ElasticSearch" />
</appSettings>
<!--
For a description of web.config changes see http://go.microsoft.com/fwlink/?LinkId=235367.
The following attributes can be set on the <httpRuntime> tag.
<system.Web>
<httpRuntime targetFramework="4.5.1" />
</system.Web>
-->
<system.web>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
<customErrors mode="Off" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-8.0.0.0" newVersion="8.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<system.webServer>
<handlers>
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<remove name="OPTIONSVerbHandler" />
<remove name="TRACEVerbHandler" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="*" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
<staticContent>
<remove fileExtension=".woff"/>
<remove fileExtension=".woff2"/>
<remove fileExtension=".svg"/>
<mimeMap fileExtension=".woff" mimeType="application/x-font-woff" />
<mimeMap fileExtension=".woff2" mimeType="application/x-font-woff" />
<mimeMap fileExtension=".svg" mimeType="image/svg+xmz" />
</staticContent>
</system.webServer>
<system.net>
<settings>
<httpWebRequest useUnsafeHeaderParsing="false" />
</settings>
</system.net>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
MVC6的配置
首先,MVC的默認配置變成了JSON文件。(ASP.NET Core的配置管理支持XML,JSON,INI三種方式。)
你可以將配置文件做成自己喜歡的文件格式,或者多個文件格式混用。
(以下示例代碼來自 XiaoFaye的Github開源示例,三個配置文件的內容這里省略了,詳細請參見Github)
using System;
using Microsoft.Extensions.Configuration;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
var builder = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.AddXmlFile("appsettings.xml")
.AddIniFile("appsettings.ini");
builder.AddEnvironmentVariables();
IConfigurationRoot Configuration = builder.Build();
Console.WriteLine("Read json configuration file: " + Configuration["JsonData:DefaultConnection:ConnectionString"]);
Console.WriteLine(".");
Console.WriteLine(".");
Console.WriteLine("Read xml configuration file: ");
Console.WriteLine("Xml node content: " + Configuration["DefaultConnection"]);
Console.WriteLine("Xml node attribute 1: " + Configuration["DefaultConnection:key"]);
Console.WriteLine("Xml node attribute 2: " + Configuration["DefaultConnection:value"]);
Console.WriteLine(".");
Console.WriteLine(".");
Console.WriteLine("Read ini configuration file: " + Configuration["IniData:DefaultConnection"]);
}
}
}
典型的Project.Json
Converting an ASP.NET Core RC1 Project to RC2
配置文件比較長,這里就不再完整列出了,如果你想查看一個完整的例子。請使用以下鏈接
這里有一個注意點,ASP.NET Core可以同時支持經典的NET Framework 和 NET Core,使用哪個Framework,可以在配置里面定義。
- 如果你想使用全新的.NET Core的Framework ,請這樣配置你的 framework 節
"frameworks": {
"netcoreapp1.0": {
"imports": [
"dotnet5.6",
"dnxcore50",
"portable-net45+win8"
]
}
},
- 如果您想使用.NET Framework 4.5.x,請這樣配置你的 framework 節
"frameworks": {
"net452": { }
},
如果您想知道兩個Framework之間的區別您可以閱讀本站以下文章:
補充知識 .Net Framework .Net Core Mono 區別聯系
一個簡單的配置文件
{
"version": "1.0.0-*",
"buildOptions": {
"preserveCompilationContext": true,
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.AspNetCore.Mvc": "1.0.0-*",
"Microsoft.AspNetCore.Mvc.TagHelpers": "1.0.0-*",
"Microsoft.AspNetCore.Diagnostics": "1.0.0-*",
"Microsoft.AspNetCore.StaticFiles": "1.0.0-*",
"Microsoft.AspNetCore.Server.IISIntegration": "1.0.0-*",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0-*",
"Microsoft.Extensions.Logging.Console": "1.0.0-*",
"Microsoft.Extensions.Logging.Debug": "1.0.0-*",
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.0-rc2-3002700"
}
},
"frameworks": {
"netcoreapp1.0": {
"imports": "dnxcore50"
}
}
}
典型的appsettings.json
有一些關於應用程序業務邏輯,環境配置的參數,原來也是寫在Web.config里面的,現在這個版本可以放到appsettings.json
我們看一下官方自動生成的appsettings.json是什么樣子的。
數據庫的連接字符串,日志設定,這些被放到了appsettings.json里面了。
{
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-NetCoreWeb-dff472d2-ddfc-4d7a-bb9c-19ab91e3564f;Trusted_Connection=True;MultipleActiveResultSets=true"
},
"Logging": {
"IncludeScopes": false,
"LogLevel": {
"Default": "Debug",
"System": "Information",
"Microsoft": "Information"
}
}
}
注意:和project.json這個第一等公民不同,appsettings.json屬於第二等公民(可選非必需)
它需要在啟動的時候,引入Configuration系統。當然,筆者認為,即使你修改名稱也是可以的,只要代碼里面也相應修改即可。
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);
使用方法是這樣的:
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
當然,如果你仔細研究的話,web.config文件還是有的。應該是在IIS模式的時候,IIS是必須有web.config的(可能不對,請指正)。
這里增加了AspNetCoreModule這個Handler。
IIS Support Baked In
IIS is a tremendous web server and we continue to provide first-class support for it. Use the new ASP.NET Core Module in your web.config (it’s added in the new project templates) to configure IIS to launch and host your application.
IIS是一個極其重要的Web服務器,我們繼續為其提供最高等級的支持。使用新的ASP.NET Core Module在你的Web.config中,用來配置你的IIS,使其可以運行和作為你的應用程式的宿主。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<!--
Configure your application settings in appsettings.json. Learn more at http://go.microsoft.com/fwlink/?LinkId=786380
-->
<system.webServer>
<handlers>
<add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified"/>
</handlers>
<aspNetCore processPath="%LAUNCHER_PATH%" arguments="%LAUNCHER_ARGS%" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" forwardWindowsAuthToken="false"/>
</system.webServer>
</configuration>
參考文獻
Converting an ASP.NET Core RC1 Project to RC2
ASP.NET官網Configuration
XiaoFaye的XiaoFaye/netcore-samples Github
Artech 博客園系列文章 .NET Core全新的配置管理[共9篇]
解讀ASP.NET 5 & MVC6系列(5):Configuration配置信息管理