【问题标题】:How do I set the request timeout for dynamically loaded assembly (controller) in an ASP.NET Core如何在 ASP.NET Core 中为动态加载的程序集(控制器)设置请求超时
【发布时间】:2021-08-10 09:12:36
【问题描述】:

我尝试使用以下代码动态加载控制器类型的程序集。

var mvcBuilder = services
                .AddMvc(config =>
                    {
                        var policy = new AuthorizationPolicyBuilder()
                            .RequireAuthenticatedUser()
                            .Build();
                        config.Filters.Add(new AuthorizeFilter(policy));
                        config.EnableEndpointRouting = false;
                    })
                .AddSessionStateTempDataProvider()
                .ConfigureApplicationPartManager(m => m.FeatureProviders.Add(new RemoteControllerFeatureProvider(listOfPaths, Logger)))
                .AddNewtonsoftJson(op => { op.UseMemberCasing(); })
                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
            
mvcBuilder.Services.AddSession(option => {
                option.IdleTimeout = TimeSpan.FromSeconds(600);
                option.Cookie.HttpOnly = true;
                option.Cookie.IsEssential = true;
            });

return mvcBuilder;

这一行负责动态加载程序集:

.ConfigureApplicationPartManager(m => m.FeatureProviders.Add(new RemoteControllerFeatureProvider(listOfPaths, Logger)))

RemoteControllerFeatureProvider 类实现了IApplicationFeatureProvider<ControllerFeature> 接口,PopulateFeature() 方法如下所示:

public void PopulateFeature(IEnumerable<ApplicationPart> parts, ControllerFeature feature)
{
    string path = @"..\ClassLibProject\bin\Debug\netcoreapp3.1\ClassLibProject.dll";

    try
    {
        var asm = Assembly.LoadFrom(path);
        var t = asm.GetTypes();

        foreach (var item in t)
        {
            if (item.BaseType == typeof(Microsoft.AspNetCore.Mvc.Controller))
            {
                feature.Controllers.Add(item.GetTypeInfo());
            }
        }
    }
    catch (Exception ex)
    {
        _log.Debug($"Cannot load {System.IO.Path.GetFileName(path)}. {ex.Message}");
    }
}

现在这个ClassLibProjectController 类型,它会抛出502.3 Bad Gateway 错误。因为有一个操作耗时超过 2 分钟(目前不专注于优化那个逻辑)。

ClassLibProject 装饰有过滤器属性[MiddlewareFilter(typeof(SessionPipeline))]

现在的问题是,有没有办法为这个 ClassLibProject 控制器设置请求超时,这样我就不会收到 502.3 Bad Gateway 错误。

如果我犯了任何错误,请纠正我。

【问题讨论】:

    标签: c# .net-core asp.net-core-middleware


    【解决方案1】:

    我看错了方向。我只需要在我的 API 项目的 web.config 文件中更改 requestTimeout 参数。我做到了,而且运行顺利。

    【讨论】:

      猜你喜欢
      • 2010-10-09
      • 2017-11-16
      • 2019-03-11
      • 1970-01-01
      • 2018-03-03
      • 1970-01-01
      • 2021-11-21
      • 2013-09-17
      • 1970-01-01
      相关资源
      最近更新 更多