如何将 ASP.NET Framework 配置迁移到 ASP.NET Core? [英] How to migrate ASP.NET Framework configurations to ASP.NET Core?

查看:50
本文介绍了如何将 ASP.NET Framework 配置迁移到 ASP.NET Core?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将 IIS 上托管的 ASP.NET Framework 应用程序迁移到 Kestrel 上托管的 ASP.NET Core.

I'm migrating an ASP.NET Framework application hosted on IIS to ASP.NET Core hosted on Kestrel.

在 ASP.NET Framework 中,我有一个带有数十个自定义配置/优化的 web.config,例如:

In ASP.NET Framework, I have a web.config with dozens of custom configurations/optimizations, like:

<httpRuntime executionTimeout="120" maxUrlLength="8192" maxQueryStringLength="8192" />

问题是我找不到如何配置这些设置,例如在 ASP.NET Core 中使用 Kestrel 配置 maxQueryStringLength.

Problem is that I can't find how to configuration those settings, like maxQueryStringLength in ASP.NET Core with Kestrel.

例如,在这个答案中,用户说它在 ASP.NET Core 中不可用并建议使用 IIS 或 NGINX.

For example, in this answer, the user says that it is not available in ASP.NET Core and recommends to use IIS or NGINX.

如何在不使用 ASP.NET Core 中的 web.config 文件的情况下迁移我的 web.config 设置?我更喜欢使用默认的 appsettings.json 文件.

How can I migrate my web.config settings without using a web.config file in ASP.NET Core? I would prefer to use the default appsettings.json file.

推荐答案

您可以使用 ASP.NET Core Kestrel 限制来进行适当的配置

You may use ASP.NET Core Kestrel limits to make the appropriate configs

https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.server.kestrel.core.kestrelserverlimits?view=aspnetcore-3.1

可以通过 Program.cs 中的配置来完成

It could be done via configs in Program.cs

#elif Limits
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    #region snippet_Limits
                    webBuilder.ConfigureKestrel(serverOptions =>
                    {
                        serverOptions.Limits.MaxConcurrentConnections = 100;
                        serverOptions.Limits.MaxConcurrentUpgradedConnections = 100;
                        serverOptions.Limits.MaxRequestBodySize = 10 * 1024;
                        serverOptions.Limits.MinRequestBodyDataRate =
                            new MinDataRate(bytesPerSecond: 100, 
                                gracePeriod: TimeSpan.FromSeconds(10));
                        serverOptions.Limits.MinResponseDataRate =
                            new MinDataRate(bytesPerSecond: 100, 
                                gracePeriod: TimeSpan.FromSeconds(10));
                        serverOptions.Listen(IPAddress.Loopback, 5000);
                        serverOptions.Listen(IPAddress.Loopback, 5001, 
                            listenOptions =>
                            {
                                listenOptions.UseHttps("testCert.pfx", 
                                    "testPassword");
                            });
                        serverOptions.Limits.KeepAliveTimeout = 
                            TimeSpan.FromMinutes(2);
                        serverOptions.Limits.RequestHeadersTimeout = 
                            TimeSpan.FromMinutes(1);
                    })
                    #endregion
                    .UseStartup<Startup>();
                });
#elif Port0

Kestrel 选项也可以使用配置提供程序进行设置.例如,文件配置提供程序 ( https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#file-configuration-provider )可以从appsettings.json 或 appsettings.{Environment}.json 文件:

Kestrel options can also be set using a configuration provider. For example, the File Configuration Provider ( https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-3.1#file-configuration-provider ) can load Kestrel configuration from an appsettings.json or appsettings.{Environment}.json file:

{
  "Kestrel": {
    "Limits": {
      "MaxConcurrentConnections": 100,
      "MaxConcurrentUpgradedConnections": 100
    },
    "DisableStringReuse": true
  }
}

另外,如果你需要通过代码来管理这些东西,你可以尝试通过中间件来处理它

Also, if you need to manage these things via code you may try to handle it via middleware

public class RequestFilterMiddleware
    {
        private readonly RequestDelegate _next;
        private const long _allowedRequestQueryStringMaxLength = 100;
        private const long _allowedUrlStringMaxLength = 100;
        public RequestFilterMiddleware(RequestDelegate next)
        {
            _next = next;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            var queryStringLength = httpContext.Request.QueryString.Value?.Length;
            if (queryStringLength > _allowedRequestQueryStringMaxLength)
            {
                //throw exception or send some appropriate http status code
            }

            var urlRequestLength = httpContext.Request.GetDisplayUrl().Length;
            if (urlRequestLength > _allowedUrlStringMaxLength)
            {
                //throw exception or send some appropriate http status code
            }

            using (var TokenSource = System.Threading.CancellationTokenSource.CreateLinkedTokenSource(httpContext.RequestAborted))
            {
                httpContext.RequestAborted = TokenSource.Token;
                var DelayTask = Task.Delay(500, TokenSource.Token);
                var NextTask = _next.Invoke(httpContext);
                if (await Task.WhenAny(DelayTask, NextTask).ConfigureAwait(false) == DelayTask)
                {
                    //LogStuff for long running requests
                   
                }
                TokenSource.Cancel();
            }

            await _next(httpContext);
        }
    }

遗憾的是,此时 Kestrel 中不提供超时选项,要获取更多信息,您可以阅读此主题 https://github.com/dotnet/aspnetcore/issues/10079

Unfortunately, the timeout option is not available in Kestrel at this moment, to get more information you may read this topic https://github.com/dotnet/aspnetcore/issues/10079

但是,至少可以在生产中记录长时间运行的请求以供以后优化.

However, it's possible at least to log long running requests in production for later optimization purposes.

这篇关于如何将 ASP.NET Framework 配置迁移到 ASP.NET Core?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆