从ASP.NET到ASP.NET Core差异变化

MSDN原文:链接

ASP.NET Core项目为开发人员提供了针对.NET Core,.NET Framework2种实现方式,根据官网通告NETCORE3.0后将取消对.NET Framework的支持。

NET Framework下使用

在针对.NET Framework时,项目需要引用NuGet AspNetCore包。

<ItemGroup>
   <PackageReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>

 

项目结构差异:

.csproj的文件在ASP.NET Core下进行了简化:

  • 明确包含文件不是他们被视为项目的一部分。这可以降低在处理大型团队时出现XML合并冲突的风险。

  • 没有其他项目的基于GUID的引用,这提高了文件的可读性。

  • 可以在不在Visual Studio中卸载文件的情况下编辑该文件 

 程序入口和Global.asax文件变更:

     ASP.NET Core引入了新的引导应用程序机制,ASP.NET 中入口点是Global.asax文件。路径配置和过滤器以及区域注册等任务在Global.asax文件中处理

public class MvcApplication : System.Web.HttpApplication
{
    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }
}

此方法以干扰实现的方式将应用程序与其部署的服务器耦合在一起。为了解耦,OWIN被引入以提供一种更清晰的方式来一起使用多个框架。OWIN提供了一个管道,只添加所需的模块。托管环境采用Startup功能来配置服务和应用程序的请求管道。

使用ASP.NET Core 后,应用程序的入口点是Startup,不再依赖Global.asax。

ASP.NET CORE  +NET Framework 实现(这会配置您的默认路由,默认为Json上的XmlSerialization。根据需要将其他中间件添加到此管道(加载服务,配置设置,静态文件等):

using Owin;
using System.Web.Http;

namespace WebApi
{
    // Note: By default all requests go through this OWIN pipeline. Alternatively you can turn this off by adding an appSetting owin:AutomaticAppStartup with value “false”. 
    // With this turned off you can still have OWIN apps listening on specific routes by adding routes in global.asax file using MapOwinPath or MapOwinRoute extensions on RouteTable.Routes
    public class Startup
    {
        // Invoked once at startup to configure your application.
        public void Configuration(IAppBuilder builder)
        {
            HttpConfiguration config = new HttpConfiguration();
            config.Routes.MapHttpRoute("Default", "{controller}/{customerID}", new { controller = "Customer", customerID = RouteParameter.Optional });

            config.Formatters.XmlFormatter.UseXmlSerializer = true;
            config.Formatters.Remove(config.Formatters.JsonFormatter);
            // config.Formatters.JsonFormatter.UseDataContractJsonSerializer = true;

            builder.UseWebApi(config);
        }
    }
}

 

ASP.NET CORE+Net Core实现中使用类似的方法,但不依赖于OWIN,相反,通过Program.cs Main方法(类似于控制台应用程序)完成的,并通过Startup加载。

using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;

namespace WebApplication2
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateWebHostBuilder(args).Build().Run();
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }
}

 

Startup必须包括一种Configure方法。Configure,向管道添加必要的中间件。在以下示例中(来自默认网站模板),扩展方法配置管道,并支持:

  • 错误页面
  • HTTP严格传输安全性
  • HTTP重定向到HTTPS
  • ASP.NET核心MVC 
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseMvc();
}

Appliction和Host已经分离,这为迁移到不同平台提供了灵活性。

配置文件差异:

ASP.NET支持存储配置。例如,这些设置用于支持部署应用程序的环境。通常的做法是将所有自定义键值对存储<appSettings>Web.config文件部分中

<appSettings>
  <add key="UserName" value="User" />
  <add key="Password" value="Password" />
</appSettings>

 

ASP.NET 应用程序使用命名空间中ConfigurationManager.AppSettings集合读取这些设置System.Configuration

string userName = System.Web.Configuration.ConfigurationManager.AppSettings["UserName"];
string password = System.Web.Configuration.ConfigurationManager.AppSettings["Password"];

 

ASP.NET Core可以将应用程序的配置数据存储在任何文件中,并将其作为中间件引导的一部分加载。项目模板中使用的默认文件是appsettings.json

{
  "Logging": {
    "IncludeScopes": false,
    "LogLevel": {
      "Default": "Debug",
      "System": "Information",
      "Microsoft": "Information"
    }
  },
  // Here is where you can supply custom configuration settings, Since it is is JSON, everything is represented as key: value pairs
  // Name of section is your choice
  "AppConfiguration": {
    "UserName": "UserName",
    "Password": "Password"
  }
}

通过Startup.csappsettings.json文件加载到IConfiguration应用程序内部的实例中

public Startup(IConfiguration configuration)
{
    Configuration = configuration;
}

public IConfiguration Configuration { get; }

读取Configuration以获取设置

string userName = Configuration.GetSection("AppConfiguration")["UserName"];
string password = Configuration.GetSection("AppConfiguration")["Password"];

对于更深入的参考ASP.NET Core配置,请查看 在ASP.NET核心配置

 

posted @ 2019-06-20 09:44  Merray  Views(2021)  Comments(0Edit  收藏  举报