【问题标题】:ASP.NET Core 5 MVC : httpContext.User not authenticated in custom CultureProviderASP.NET Core 5 MVC:httpContext.User 未在自定义 CultureProvider 中进行身份验证
【发布时间】:2021-11-06 21:30:47
【问题描述】:

我必须在我的网络应用程序中添加本地化。

请求是 grpc 服务将为所有用户提供默认语言,因此在启动时我试图读取该值但不知道如何在 new CustomRequestCultureProvider 中使用已注册的服务

public static CultureInfo[] supportedCultures = new[] { new CultureInfo("it-IT"), new CultureInfo("en-US")};

public void ConfigureServices(IServiceCollection services)
{
    services.AddTransient<ISpaClient, GrpcSpaClient>();

    services.AddLocalization(options => options.ResourcesPath = "Resources");
    services.AddMvc()
            .AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix)
            .AddDataAnnotationsLocalization();

    services.Configure<RequestLocalizationOptions>(options =>
        {
            options.DefaultRequestCulture = new RequestCulture(culture: supportedCultures[0].ToString(), uiCulture: supportedCultures[0].ToString());
            options.SupportedCultures = supportedCultures;
            options.SupportedUICultures = supportedCultures;

            options.RequestCultureProviders.Clear();
            options.RequestCultureProviders.Add(new MyCustomRequestCultureProvider());
        });
}

我的自定义类

public class MyCustomRequestCultureProvider : RequestCultureProvider
{
    public override async Task<ProviderCultureResult> DetermineProviderCultureResult(HttpContext httpContext)
    {
        await Task.Yield();

        if (httpContext == null)
        {
            throw new ArgumentNullException(nameof(httpContext));
        }

        if (!httpContext.User.Identity.IsAuthenticated)
        {
            return null;
        }
        
        var culture = httpContext.User
                                 .Claims
                                 .FirstOrDefault(c => c.Type == TipoClaim.linguaPredefinita.ToString())?
                                 .Value;

        if (culture == null)
        {
            return null;
        }

        return new ProviderCultureResult(culture);
    }
}

但是这里httpContext.User 永远不是Authenticated,即使页面是

【问题讨论】:

    标签: .net localization asp.net-core-mvc claims-based-identity


    【解决方案1】:

    我的最佳猜测是您在 UseAuthentication 之前调用了 UseRequestLocalization。

    【讨论】:

    猜你喜欢
    • 2017-02-15
    • 2016-07-05
    • 1970-01-01
    • 2018-02-24
    • 2018-03-15
    • 1970-01-01
    • 2021-05-31
    相关资源
    最近更新 更多