.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();

 

posted @ 2022-08-26 16:25  hao_1234_1234  阅读(297)  评论(0编辑  收藏  举报