.net core 壓縮數據、用戶響應壓縮

https://docs.microsoft.com/zh-cn/aspnet/core/performance/response-compression?view=aspnetcore-6.0

 

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddResponseCompression(options =>
{
  options.EnableForHttps = true;
});

var app = builder.Build();

app.UseResponseCompression();//用戶響應壓縮,全局有效(只有這一行代碼)

app.MapGet("/", () => "Hello World!");

app.Run();

 

實際使用 Program

//響應壓縮
services.AddResponseCompression();
using Autofac;
using Autofac.Extensions.DependencyInjection;
using Demo.Infrastructure;
using Demo.LogService.Context;
using Demo.Model;
using Demo.Repository;
using Demo.Web.AutofacRegister;
using Demo.Web.Common;
using Demo.Web.Models;
using log4net.Config;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.ResponseCompression;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting.WindowsServices;
using System.IO.Compression;
using System.Reflection;
using System.Text.Encodings.Web;
using System.Text.Unicode;

var options = new WebApplicationOptions
{
    Args = args,
    ContentRootPath = WindowsServiceHelpers.IsWindowsService() ? AppContext.BaseDirectory : default,
};

var builder = WebApplication.CreateBuilder(options);
var services = builder.Services;
var Configuration = builder.Configuration;
//響應壓縮
services.AddResponseCompression();


// Add services to the container.
builder.Services.AddControllersWithViews().AddJsonOptions(options =>
{
    options.JsonSerializerOptions.Converters.Add(new DateTimeConverter());
    options.JsonSerializerOptions.Encoder = JavaScriptEncoder.Create(UnicodeRanges.All);
    //options.JsonSerializerOptions.PropertyNamingPolicy = System.Text.Json.JsonNamingPolicy.CamelCase;
    options.JsonSerializerOptions.PropertyNamingPolicy = null;
});

builder.Host.UseWindowsService().ConfigureAppConfiguration((hostingContext, config) =>
{
    config.AddJsonFile("endpoint.json", optional: true, reloadOnChange: true);
    config.AddEnvironmentVariables();
});


string configFilePath = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "\\log4net.config";
XmlConfigurator.ConfigureAndWatch(new FileInfo(configFilePath));


builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
builder.Host.ConfigureContainer<ContainerBuilder>(builder =>
{
    //直接用Autofac註冊我們自定義的模塊
    builder.RegisterModule(new CustomAutofacModule());
    //註冊實例
    builder.RegisterInstance(new Encryption(Configuration["AppSettings:AesKey"], Configuration["AppSettings:AesIV"])).As<IEncryption>();
    builder.RegisterInstance(new ClientEncryption(Configuration["AppSettings:ClientAesKey"], Configuration["AppSettings:ClientAesIV"])).As<IClientEncryption>();
    //builder.RegisterType<MongoDbContext>().InstancePerLifetimeScope();
    //註冊要通過反射創建的組件。
    builder.RegisterType<HttpContextAccessor>().As<IHttpContextAccessor>().InstancePerLifetimeScope();
});


//添加身份驗證
//builder.Services.AddAuthentication(options =>
//{
//    //添加身份驗證方案。
//    options.AddScheme<AppAuthentication>(AppAuthentication.SchemeName, "default scheme");
//    //默認身份驗證方案
//    options.DefaultAuthenticateScheme = AppAuthentication.SchemeName;
//    //默認挑戰者方案
//    options.DefaultChallengeScheme = AppAuthentication.SchemeName;
//});

builder.Services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(options =>
{
    options.LoginPath = new PathString("/Account/Login");
    options.ExpireTimeSpan = new TimeSpan(1, 0, 0);
    builder.Configuration.Bind("CookieSettings", options);

});



services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));

//添加EFCoreDbContext數據庫上下文配置文件(默認AddDbContext內部註冊服務的聲明週期爲AddScoped)
services.AddDbContextPool<DemoDataContext>(options =>
{
    options.UseSqlServer(Configuration.GetConnectionString("HDataConnectionString"));
});
services.AddDbContextPool<DemoLogDataContext>(options =>
{
    options.UseSqlServer(Configuration.GetConnectionString("DemoLogDataConnectionString"));
});


//添加對象-對象映射器AutoMapper
services.AddAutoMapper(Assembly.GetExecutingAssembly());


var app = builder.Build();

app.UsePathBase("/Demo");
app.UseResponseCompression();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.UseStaticFiles();

app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");
app.Run();

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章