2016-06-08 118 views

回答

0

看看這個Post。他們使用我剛剛測試過的中間件方法,它似乎正在工作。對於asp.net核心將是這樣的:

public void Configure(IApplicationBuilder app, ILoggerFactory loggerFactory) 
{ 
    loggerFactory.AddConsole(LogLevel.Debug); 

    app.Use(async (context, next) => { 
     context.Response.Headers.Remove("Content-Type"); 
     context.Response.Headers.Add("Content-encoding", "gzip"); 
     context.Response.Headers.Add("Content-Type", "application/json"); 
     context.Response.Body = new System.IO.Compression.GZipStream(context.Response.Body, System.IO.Compression.CompressionMode.Compress); 
     await next(); 
     await context.Response.Body.FlushAsync(); 
    }) 
    .UseMvc(); 
} 

您也可以嘗試玩弄IResultFilter.OnActionExecuted,因爲它是可能的結果只是尚未計算。

1

我一直在使用http://www.webpagetest.org/進行測試,我的AspNetCore站點託管在SmarterAsp.Net上 - >我必須執行以下操作才能獲得A壓縮。

添加這種依賴性:

"System.IO.Compression": "4.1.0-rc2-24027", 

而且我startup.cs:

public void Configure(IApplicationBuilder app) 
    { 
     app.Use(async (context, next) => 
     { 
      context.Response.Headers.Add("Content-encoding", "gzip"); 
      context.Response.Body = new System.IO.Compression.GZipStream(context.Response.Body, 
       System.IO.Compression.CompressionMode.Compress); 
      await next(); 
      await context.Response.Body.FlushAsync(); 
     }); 
3

壓縮是在ASP.net核心1.1中的新功能:

這是包,你會需要。 https://www.nuget.org/packages/Microsoft.AspNetCore.ResponseCompression/

這裏是展示如何使用它的一些微軟官方視頻:https://youtu.be/IfLg6LQCl-Y?t=223

一些背景資料:https://github.com/aspnet/BasicMiddleware/issues/34

代碼:

Project.json:

"dependencies": { 
    ..., 
    "Microsoft.AspNetCore.ResponseCompression": "1.0.0" 
} 

啓動。 cs:

public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
{ 
    ... 
    //Add Middleware 
    app.UseResponseCompression(); 
    ... 
} 

public void ConfigureServices(IServiceCollection services) 
{ 
    //Configure Compression level 
    services.Configure<GzipCompressionProviderOptions>(options => options.Level = CompressionLevel.Fastest); 

    //Add Response compression services 
    services.AddResponseCompression(options => 
    { 
    options.Providers.Add<GzipCompressionProvider>(); 
    }); 
}