У меня есть приложение .net core 2.2 mvc с аутентификацией Windows, и у меня есть собственный HttpContext, настроенный как промежуточное ПО.В моем домашнем контроллере я хочу получить различные данные о текущем пользователе.Когда приложения загружаются, все работает так, как вы ожидаете, но если вы обновляете браузер, он завершается с ошибкой в строке
string UserIdentityName = MyHttpContext.Current.User.Identity.Name;
с ошибкой «System.ObjectDisposedException: безопасный дескриптор закрыт» - TargetSite {VoidDangerousAddRef (Boolean ByRef)}
Пожалуйста, помогите.
HttpContextMiddleware.cs:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
public class MyHttpContext
{
private static IHttpContextAccessor m_httpContextAccessor;
public static HttpContext Current => m_httpContextAccessor.HttpContext;
public static string AppBaseUrl => $"{Current.Request.Scheme}://{Current.Request.Host}{Current.Request.PathBase}";
internal static void Configure(IHttpContextAccessor contextAccessor)
{
m_httpContextAccessor = contextAccessor;
}
}
public static class HttpContextExtensions
{
public static void AddHttpContextAccessor(this IServiceCollection services)
{
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
}
public static IApplicationBuilder UseHttpContext(this IApplicationBuilder app)
{
MyHttpContext.Configure(app.ApplicationServices.GetRequiredService<IHttpContextAccessor>());
return app;
}
}
StartUp.cs:
using CoreIV_Admin_Core.Helpers;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Server.IISIntegration;
using Microsoft.AspNetCore.SpaServices.Webpack;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using NLog;
namespace CoreIV_Admin_Core
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public static IConfiguration Configuration
{
get; set;
}
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
//services.TryAddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.Configure<AppConfig>(options => Configuration.GetSection("AppConfig").Bind(options));
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
//services.AddHttpContextAccessor();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
app.UseWebpackDevMiddleware(new WebpackDevMiddlewareOptions
{
HotModuleReplacement = true
});
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
LogManager.Configuration.Variables["logdir"] = Configuration["AppConfig:logDirectory"];
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseCookiePolicy();
app.UseHttpContext();
app.UseAuthentication();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
routes.MapSpaFallbackRoute(
name: "spa-fallback",
defaults: new
{
controller = "Home",
action = "Index"
});
});
}
}
}