Догађаји
Поwер БИ ДатаВиз Светско првенство
14. феб 16 - 31. мар 16
Са 4 шансе за улазак, можете освојити конференцијски пакет и стићи до ЛИВЕ Гранд Финале у Лас Вегасу
Сазнајте вишеОвај прегледач више није подржан.
Надоградите на Microsoft Edge бисте искористили најновије функције, безбедносне исправке и техничку подршку.
Network bandwidth is a limited resource. Reducing the size of the response usually increases the responsiveness of an app, often dramatically. One way to reduce payload sizes is to compress an app's responses.
Compressed responses over secure connections can be controlled with the EnableForHttps option, which is disabled by default because of the security risk. Using compression with dynamically generated pages can expose the app to CRIME and BREACH attacks. CRIME and BREACH attacks can be mitigated in ASP.NET Core with antiforgery tokens. For more information, see Prevent Cross-Site Request Forgery (XSRF/CSRF) attacks in ASP.NET Core. For information on mitigating BREACH attacks, see mitigations at http://www.breachattack.com/
Even when EnableForHttps
is disabled in the app, IIS, IIS Express, and Azure App Service can apply gzip at the IIS web server. When reviewing response headers, take note of the Server value. An unexpected content-encoding
response header value may be the result of the web server and not the ASP.NET Core app configuration.
Use server-based response compression technologies in IIS, Apache, or Nginx. The performance of the response compression middleware probably won't match that of the server modules. HTTP.sys server and Kestrel server don't currently offer built-in compression support.
Use Response Compression Middleware when the app is:
Usually, any response not natively compressed can benefit from response compression. Responses not natively compressed typically include CSS, JavaScript, HTML, XML, and JSON. Don't compress natively compressed assets, such as PNG files. When attempting to further compress a natively compressed response, any small extra reduction in size and transmission time will likely be overshadowed by the time it takes to process the compression. Don't compress files smaller than about 150-1000 bytes, depending on the file's content and the efficiency of compression. The overhead of compressing small files may produce a compressed file larger than the uncompressed file.
When a client can process compressed content, the client must inform the server of its capabilities by sending the Accept-Encoding
header with the request. When a server sends compressed content, it must include information in the Content-Encoding
header on how the compressed response is encoded. Content encoding designations supported by the response compression middleware are shown in the following table.
Accept-Encoding header values |
Middleware Supported | Description |
---|---|---|
br |
Yes (default) | Brotli compressed data format |
deflate |
No | DEFLATE compressed data format |
exi |
No | W3C Efficient XML Interchange |
gzip |
Yes | Gzip file format |
identity |
Yes | "No encoding" identifier: The response must not be encoded. |
pack200-gzip |
No | Network Transfer Format for Java Archives |
* |
Yes | Any available content encoding not explicitly requested |
For more information, see the IANA Official Content Coding List.
The response compression middleware allows adding additional compression providers for custom Accept-Encoding
header values. For more information, see Custom Providers in this article.
The response compression middleware is capable of reacting to quality value (qvalue, q
) weighting when sent by the client to prioritize compression schemes. For more information, see RFC 9110: Accept-Encoding.
Compression algorithms are subject to a tradeoff between compression speed and the effectiveness of the compression. Effectiveness in this context refers to the size of the output after compression. The smallest size is achieved by the optimal compression.
The headers involved in requesting, sending, caching, and receiving compressed content are described in the following table.
Header | Role |
---|---|
Accept-Encoding |
Sent from the client to the server to indicate the content encoding schemes acceptable to the client. |
Content-Encoding |
Sent from the server to the client to indicate the encoding of the content in the payload. |
Content-Length |
When compression occurs, the Content-Length header is removed, since the body content changes when the response is compressed. |
Content-MD5 |
When compression occurs, the Content-MD5 header is removed, since the body content has changed and the hash is no longer valid. |
Content-Type |
Specifies the MIME type of the content. Every response should specify its Content-Type . The response compression middleware checks this value to determine if the response should be compressed. The response compression middleware specifies a set of default MIME types that it can encode, and they can bed replaced or added. |
Vary |
When sent by the server with a value of Accept-Encoding to clients and proxies, the Vary header indicates to the client or proxy that it should cache (vary) responses based on the value of the Accept-Encoding header of the request. The result of returning content with the Vary: Accept-Encoding header is that both compressed and uncompressed responses are cached separately. |
Explore the features of the Response Compression Middleware with the sample app. The sample illustrates:
The following code shows how to enable the Response Compression Middleware for default MIME types and compression providers (Brotli and Gzip):
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
});
var app = builder.Build();
app.UseResponseCompression();
app.MapGet("/", () => "Hello World!");
app.Run();
Notes:
EnableForHttps
to true
is a security risk. See Compression with HTTPS in this article for more information.app.UseResponseCompression
must be called before any middleware that compresses responses. For more information, see ASP.NET Core Middleware.Accept-Encoding
request header and examine the response headers, size, and body.Submit a request to the sample app without the Accept-Encoding
header and observe that the response is uncompressed. The Content-Encoding
header isn't in the Response Headers collection.
For example, in Firefox Developer:
Accept-Encoding:
from gzip, deflate, br
to none
.Submit a request to the sample app with a browser using the developer tools and observe that the response is compressed. The Content-Encoding
and Vary
headers are present on the response.
Use the BrotliCompressionProvider to compress responses with the Brotli compressed data format.
If no compression providers are explicitly added to the CompressionProviderCollection:
Напомена
Documentation links to .NET reference source usually load the repository's default branch, which represents the current development for the next release of .NET. To select a tag for a specific release, use the Switch branches or tags dropdown list. For more information, see How to select a version tag of ASP.NET Core source code (dotnet/AspNetCore.Docs #26205).
When a compression provider is added, other providers aren't added. For example, if the Gzip compression provider is the only provider explicitly added, no other compression providers are added.
The following code:
using System.IO.Compression;
using Microsoft.AspNetCore.ResponseCompression;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
});
builder.Services.Configure<BrotliCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Fastest;
});
builder.Services.Configure<GzipCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.SmallestSize;
});
var app = builder.Build();
app.UseResponseCompression();
app.MapGet("/", () => "Hello World!");
app.Run();
Set the compression level with BrotliCompressionProviderOptions and GzipCompressionProviderOptions. The Brotli and Gzip compression providers default to the fastest compression level, CompressionLevel.Fastest, which might not produce the most efficient compression. If the most efficient compression is desired, configure the response compression middleware for optimal compression.
See CompressionLevel Enum for values that indicate whether a compression operation emphasizes speed or compression size.
using System.IO.Compression;
using Microsoft.AspNetCore.ResponseCompression;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
});
builder.Services.Configure<BrotliCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Fastest;
});
builder.Services.Configure<GzipCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.SmallestSize;
});
var app = builder.Build();
app.UseResponseCompression();
app.MapGet("/", () => "Hello World!");
app.Run();
Create custom compression implementations with ICompressionProvider. The EncodingName represents the content encoding that this ICompressionProvider
produces. The response compression middleware uses this information to choose the provider based on the list specified in the Accept-Encoding
header of the request.
Requests to the sample app with
the Accept-Encoding: mycustomcompression
header return a response with a Content-Encoding: mycustomcompression
header. The client must be able to decompress the custom encoding in order for a custom compression implementation to work.
using Microsoft.AspNetCore.ResponseCompression;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResponseCompression(options =>
{
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.Providers.Add<CustomCompressionProvider>();
});
var app = builder.Build();
app.UseResponseCompression();
app.MapGet("/", () => "Hello World!");
app.Run();
using Microsoft.AspNetCore.ResponseCompression;
public class CustomCompressionProvider : ICompressionProvider
{
public string EncodingName => "mycustomcompression";
public bool SupportsFlush => true;
public Stream CreateStream(Stream outputStream)
{
// Replace with a custom compression stream wrapper.
return outputStream;
}
}
With the preceding code, the response body isn't compressed by the sample. However, the sample shows where to implement a custom compression algorithm.
The response compression middleware specifies a default set of MIME types for compression. See the source code for a complete list of MIME types supported.
Напомена
Documentation links to .NET reference source usually load the repository's default branch, which represents the current development for the next release of .NET. To select a tag for a specific release, use the Switch branches or tags dropdown list. For more information, see How to select a version tag of ASP.NET Core source code (dotnet/AspNetCore.Docs #26205).
Replace or append MIME types with ResponseCompressionOptions.MimeTypes
. Note that wildcard MIME types, such as text/*
aren't supported. The sample app adds a MIME type for image/svg+xml
and compresses and serves the ASP.NET Core banner image banner.svg.
using Microsoft.AspNetCore.ResponseCompression;
using ResponseCompressionSample;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.Providers.Add<CustomCompressionProvider>();
options.MimeTypes =
ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "image/svg+xml" });
});
var app = builder.Build();
app.UseResponseCompression();
When compressing responses based on the Accept-Encoding
request header, there are can be uncompressed and multiple compressed versions of the response. In order to instruct client and proxy caches that multiple versions exist and should be stored, the Vary
header is added with an Accept-Encoding
value. The response middleware adds the Vary
header automatically when the response is compressed.
Напомена
Documentation links to .NET reference source usually load the repository's default branch, which represents the current development for the next release of .NET. To select a tag for a specific release, use the Switch branches or tags dropdown list. For more information, see How to select a version tag of ASP.NET Core source code (dotnet/AspNetCore.Docs #26205).
When a request is proxied by Nginx, the Accept-Encoding
header is removed. Removal of the Accept-Encoding
header prevents the response compression middleware from compressing the response. For more information, see NGINX: Compression and Decompression. This issue is tracked by Figure out pass-through compression for Nginx (dotnet/aspnetcore#5989).
To disable IIS Dynamic Compression Module configured at the server level, see Disabling IIS modules.
Use a tool like Firefox Browser Developer, which allows setting the Accept-Encoding
request header and study the response headers, size, and body. By default, Response Compression Middleware compresses responses that meet the following conditions:
Accept-Encoding
header is present with a value of br
, gzip
, *
, or custom encoding that matches a custom compression provider. The value must not be identity
or have a quality value (qvalue, q
) setting of 0 (zero).Content-Type
) must be set and must match a MIME type configured on the ResponseCompressionOptions.Content-Range
header.The sample app deployed to Azure has the following Program.cs
file:
using Microsoft.AspNetCore.ResponseCompression;
using ResponseCompressionSample;
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddResponseCompression(options =>
{
options.EnableForHttps = true;
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.Providers.Add<CustomCompressionProvider>();
options.MimeTypes =
ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "image/svg+xml" });
});
var app = builder.Build();
app.UseResponseCompression();
app.Map("/trickle", async (HttpResponse httpResponse) =>
{
httpResponse.ContentType = "text/plain;charset=utf-8";
for (int i = 0; i < 20; i++)
{
await httpResponse.WriteAsync("a");
await httpResponse.Body.FlushAsync();
await Task.Delay(TimeSpan.FromMilliseconds(50));
}
});
app.Map("/testfile1kb.txt", () => Results.File(
app.Environment.ContentRootFileProvider.GetFileInfo("testfile1kb.txt").PhysicalPath,
"text/plain;charset=utf-8"));
app.Map("/banner.svg", () => Results.File(
app.Environment.ContentRootFileProvider.GetFileInfo("banner.svg").PhysicalPath,
"image/svg+xml;charset=utf-8"));
app.MapFallback(() => LoremIpsum.Text);
app.Run();
Напомена
Documentation links to .NET reference source usually load the repository's default branch, which represents the current development for the next release of .NET. To select a tag for a specific release, use the Switch branches or tags dropdown list. For more information, see How to select a version tag of ASP.NET Core source code (dotnet/AspNetCore.Docs #26205).
Network bandwidth is a limited resource. Reducing the size of the response usually increases the responsiveness of an app, often dramatically. One way to reduce payload sizes is to compress an app's responses.
View or download sample code (how to download)
Use server-based response compression technologies in IIS, Apache, or Nginx. The performance of the middleware probably won't match that of the server modules. HTTP.sys server and Kestrel server don't currently offer built-in compression support.
Use Response Compression Middleware when you're:
Usually, any response not natively compressed can benefit from response compression. Responses not natively compressed typically include: CSS, JavaScript, HTML, XML, and JSON. You shouldn't compress natively compressed assets, such as PNG files. If you attempt to further compress a natively compressed response, any small additional reduction in size and transmission time will likely be overshadowed by the time it took to process the compression. Don't compress files smaller than about 150-1000 bytes (depending on the file's content and the efficiency of compression). The overhead of compressing small files may produce a compressed file larger than the uncompressed file.
When a client can process compressed content, the client must inform the server of its capabilities by sending the Accept-Encoding
header with the request. When a server sends compressed content, it must include information in the Content-Encoding
header on how the compressed response is encoded. Content encoding designations supported by the middleware are shown in the following table.
Accept-Encoding header values |
Middleware Supported | Description |
---|---|---|
br |
Yes (default) | Brotli compressed data format |
deflate |
No | DEFLATE compressed data format |
exi |
No | W3C Efficient XML Interchange |
gzip |
Yes | Gzip file format |
identity |
Yes | "No encoding" identifier: The response must not be encoded. |
pack200-gzip |
No | Network Transfer Format for Java Archives |
* |
Yes | Any available content encoding not explicitly requested |
For more information, see the IANA Official Content Coding List.
The middleware allows you to add additional compression providers for custom Accept-Encoding
header values. For more information, see Custom Providers below.
The middleware is capable of reacting to quality value (qvalue, q
) weighting when sent by the client to prioritize compression schemes. For more information, see RFC 9110: Accept-Encoding.
Compression algorithms are subject to a tradeoff between compression speed and the effectiveness of the compression. Effectiveness in this context refers to the size of the output after compression. The smallest size is achieved by the most optimal compression.
The headers involved in requesting, sending, caching, and receiving compressed content are described in the table below.
Header | Role |
---|---|
Accept-Encoding |
Sent from the client to the server to indicate the content encoding schemes acceptable to the client. |
Content-Encoding |
Sent from the server to the client to indicate the encoding of the content in the payload. |
Content-Length |
When compression occurs, the Content-Length header is removed, since the body content changes when the response is compressed. |
Content-MD5 |
When compression occurs, the Content-MD5 header is removed, since the body content has changed and the hash is no longer valid. |
Content-Type |
Specifies the MIME type of the content. Every response should specify its Content-Type . The middleware checks this value to determine if the response should be compressed. The middleware specifies a set of default MIME types that it can encode, but you can replace or add MIME types. |
Vary |
When sent by the server with a value of Accept-Encoding to clients and proxies, the Vary header indicates to the client or proxy that it should cache (vary) responses based on the value of the Accept-Encoding header of the request. The result of returning content with the Vary: Accept-Encoding header is that both compressed and uncompressed responses are cached separately. |
Explore the features of the Response Compression Middleware with the sample app. The sample illustrates:
The following code shows how to enable the Response Compression Middleware for default MIME types and compression providers (Brotli and Gzip):
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseResponseCompression();
}
}
Notes:
app.UseResponseCompression
must be called before any middleware that compresses responses. For more information, see ASP.NET Core Middleware.Accept-Encoding
request header and study the response headers, size, and body.Submit a request to the sample app without the Accept-Encoding
header and observe that the response is uncompressed. The Content-Encoding
and Vary
headers aren't present on the response.
Submit a request to the sample app with the Accept-Encoding: br
header (Brotli compression) and observe that the response is compressed. The Content-Encoding
and Vary
headers are present on the response.
Use the BrotliCompressionProvider to compress responses with the Brotli compressed data format.
If no compression providers are explicitly added to the CompressionProviderCollection:
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression();
}
The Brotli Compression Provider must be added when any compression providers are explicitly added:
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression(options =>
{
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.Providers.Add<CustomCompressionProvider>();
options.MimeTypes =
ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "image/svg+xml" });
});
}
Set the compression level with BrotliCompressionProviderOptions. The Brotli Compression Provider defaults to the fastest compression level (CompressionLevel.Fastest), which might not produce the most efficient compression. If the most efficient compression is desired, configure the middleware for optimal compression.
Compression Level | Description |
---|---|
CompressionLevel.Fastest | Compression should complete as quickly as possible, even if the resulting output isn't optimally compressed. |
CompressionLevel.NoCompression | No compression should be performed. |
CompressionLevel.Optimal | Responses should be optimally compressed, even if the compression takes more time to complete. |
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression();
services.Configure<BrotliCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Fastest;
});
}
Use the GzipCompressionProvider to compress responses with the Gzip file format.
If no compression providers are explicitly added to the CompressionProviderCollection:
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression();
}
The Gzip Compression Provider must be added when any compression providers are explicitly added:
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression(options =>
{
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.Providers.Add<CustomCompressionProvider>();
options.MimeTypes =
ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "image/svg+xml" });
});
}
Set the compression level with GzipCompressionProviderOptions. The Gzip Compression Provider defaults to the fastest compression level (CompressionLevel.Fastest), which might not produce the most efficient compression. If the most efficient compression is desired, configure the middleware for optimal compression.
Compression Level | Description |
---|---|
CompressionLevel.Fastest | Compression should complete as quickly as possible, even if the resulting output isn't optimally compressed. |
CompressionLevel.NoCompression | No compression should be performed. |
CompressionLevel.Optimal | Responses should be optimally compressed, even if the compression takes more time to complete. |
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression();
services.Configure<GzipCompressionProviderOptions>(options =>
{
options.Level = CompressionLevel.Fastest;
});
}
Create custom compression implementations with ICompressionProvider. The EncodingName represents the content encoding that this ICompressionProvider
produces. The middleware uses this information to choose the provider based on the list specified in the Accept-Encoding
header of the request.
Using the sample app, the client submits a request with the Accept-Encoding: mycustomcompression
header. The middleware uses the custom compression implementation and returns the response with a Content-Encoding: mycustomcompression
header. The client must be able to decompress the custom encoding in order for a custom compression implementation to work.
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression(options =>
{
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.Providers.Add<CustomCompressionProvider>();
options.MimeTypes =
ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "image/svg+xml" });
});
}
public class CustomCompressionProvider : ICompressionProvider
{
public string EncodingName => "mycustomcompression";
public bool SupportsFlush => true;
public Stream CreateStream(Stream outputStream)
{
// Create a custom compression stream wrapper here
return outputStream;
}
}
Submit a request to the sample app with the Accept-Encoding: mycustomcompression
header and observe the response headers. The Vary
and Content-Encoding
headers are present on the response. The response body (not shown) isn't compressed by the sample. There isn't a compression implementation in the CustomCompressionProvider
class of the sample. However, the sample shows where you would implement such a compression algorithm.
The middleware specifies a default set of MIME types for compression:
application/javascript
application/json
application/xml
text/css
text/html
text/json
text/plain
text/xml
Replace or append MIME types with the Response Compression Middleware options. Note that wildcard MIME types, such as text/*
aren't supported. The sample app adds a MIME type for image/svg+xml
and compresses and serves the ASP.NET Core banner image (banner.svg).
public void ConfigureServices(IServiceCollection services)
{
services.AddResponseCompression(options =>
{
options.Providers.Add<BrotliCompressionProvider>();
options.Providers.Add<GzipCompressionProvider>();
options.Providers.Add<CustomCompressionProvider>();
options.MimeTypes =
ResponseCompressionDefaults.MimeTypes.Concat(
new[] { "image/svg+xml" });
});
}
Compressed responses over secure connections can be controlled with the EnableForHttps
option, which is disabled by default. Using compression with dynamically generated pages can lead to security problems such as the CRIME and BREACH attacks.
When compressing responses based on the Accept-Encoding
header, there are potentially multiple compressed versions of the response and an uncompressed version. In order to instruct client and proxy caches that multiple versions exist and should be stored, the Vary
header is added with an Accept-Encoding
value. In ASP.NET Core 2.0 or later, the middleware adds the Vary
header automatically when the response is compressed.
When a request is proxied by Nginx, the Accept-Encoding
header is removed. Removal of the Accept-Encoding
header prevents the middleware from compressing the response. For more information, see NGINX: Compression and Decompression. This issue is tracked by Figure out pass-through compression for Nginx (dotnet/aspnetcore#5989).
If you have an active IIS Dynamic Compression Module configured at the server level that you would like to disable for an app, disable the module with an addition to the web.config file. For more information, see Disabling IIS modules.
Use a tool like Fiddler or Firefox Browser Developer, which allow you to set the Accept-Encoding
request header and study the response headers, size, and body. By default, Response Compression Middleware compresses responses that meet the following conditions:
Accept-Encoding
header is present with a value of br
, gzip
, *
, or custom encoding that matches a custom compression provider that you've established. The value must not be identity
or have a quality value (qvalue, q
) setting of 0 (zero).Content-Type
) must be set and must match a MIME type configured on the ResponseCompressionOptions.Content-Range
header.ASP.NET Core повратне информације
ASP.NET Core је пројекат отвореног кода. Изаберите везу да бисте обезбедили повратне информације:
Догађаји
Поwер БИ ДатаВиз Светско првенство
14. феб 16 - 31. мар 16
Са 4 шансе за улазак, можете освојити конференцијски пакет и стићи до ЛИВЕ Гранд Финале у Лас Вегасу
Сазнајте вишеОбука
Путања учења
Create cloud-native apps and services with .NET and ASP.NET Core - Training
Create independently deployable, highly scalable, and resilient apps and services using the free and open-source .NET platform. With .NET you can use popular microservice technology like Docker, Kubernetes, Dapr, Azure Container Registry, and more for .NET and ASP.NET Core applications and services.
Документација
Request decompression in ASP.NET Core
Learn how to use the request decompression middleware in ASP.NET Core
Request timeouts middleware in ASP.NET Core
Learn how to configure and use request timeout middleware in ASP.NET Core.
Tips for maximizing performance and reliability in ASP.NET Core apps.