Hi All,
I am using ASP.NET Core Web API (netcoreapp3.1) , I need to get the logged-in user name using the "User.Identity.Name" but this value always returns null, struggling for 4 days, any help is appreciated.
Below is the code reference.
Startup.cs
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.OpenApi.Models;
using Swashbuckle.AspNetCore.SwaggerUI;
using FM21.API.Extensions;
using FM21.API.Helpers;
using Microsoft.AspNetCore.Server.IISIntegration;
using AutoMapper;
using FM21.Core;
namespace FM21.API
{
public class Startup
{
//readonly string AllowNellsonOrigins = "AlowNellsonOrigins";
public Startup(IConfiguration configuration)
{
Configuration = configuration;
SetupAppConfigKeys();
ServiceExtensions.ConfigureLoggerService(configuration);
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.ConfigureCors();
services.AddMvc(options =>
{
options.Filters.Add(typeof(ValidateModelAttribute));
})
.SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
services.Configure<ApiBehaviorOptions>(options =>
{
options.SuppressModelStateInvalidFilter = true;
});
services.AddAuthentication(IISDefaults.AuthenticationScheme);
services.AddMemoryCache();
services.ConfigureIISIntegration();
services.AddHttpContextAccessor();
//services.ConfigureDBContext();
services.ConfigureRepositoryAndServices();
services.SetupAPIVersioning();
services.ConfigureControllerAndJsonSettings();
services.ConfigureLocalization();
services.ConfigureSwagger();
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
}
/// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env, IExceptionHandler exceptionHandler)
{
app.UseCors("CorsPolicy");
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseHsts();
}
app.Use(async (context, next) =>
{
app.WebWorker(context);
await next.Invoke();
});
app.UseGlobalExceptionHandler(exceptionHandler);
app.UseApiVersioning();
app.UseHttpsRedirection();
app.AddLocalization();
app.AddSwagger(env);
app.UseRouting();
app.UseAuthentication();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
exceptionHandler.LogInformation("API Started..");
}
/// <summary>
/// Fectch and set global variables
/// </summary>
public void SetupAppConfigKeys()
{
ConfigurationConstants.DbConnectionString = Configuration.GetConnectionString("AppDBContextCon");
ConfigurationConstants.EnableLog = Configuration.GetSection("AppSettings").GetValue<bool>("EnableLog");
ConfigurationConstants.LogFilePath = Configuration.GetSection("AppSettings").GetValue<string>("LogFilePath");
ConfigurationConstants.SupportedLocalization = Configuration.GetSection("AppSettings").GetValue<string>("Localization");
ConfigurationConstants.CacheDurationInSecond = Configuration.GetSection("AppSettings").GetValue<int>("CacheDurationInSecond");
ConfigurationConstants.AllowedOrigins = Configuration.GetSection("AppSettings").GetValue<string>("AllowedOrigins").Split(",");
ApplicationConstants.Domain = Configuration.GetSection("AppSettings").GetValue<string>("Domain");
ApplicationConstants.ADUserGroup = Configuration.GetSection("AppSettings").GetValue<string>("ADUserGroup");
}
}
}
Controller Code
[SwaggerOperation(Summary = "Get current window login user information", Tags = new string[] { "UserMaster" })]
[HttpGet("GetCurrentUser")]
public async Task<IActionResult> GetCurrentUser()
{
var userId = User.FindFirstValue(ClaimTypes.NameIdentifier); // will give the user's userId
var userName1 = User.FindFirstValue(ClaimTypes.Name); // will give the user's userName
string userName = _httpContextAccessor.HttpContext.User.Identity.Name;
var response = await userMasterService.GetCurrentUser(User.Identity.Name);
return new JsonResult(response);
}
ServiceExtensions.cs
using FluentValidation;
using FM21.API.Helpers;
using FM21.Core;
using FM21.Core.Localization;
//using FM21.Core.Localization;
using FM21.Core.Validator;
//using FM21.Core.Validator;
using FM21.Data;
using FM21.Data.Infrastructure;
using FM21.Data.Repository;
//using FM21.Data.Repository;
using FM21.Service;
//using FM21.Service.Caching;
//using FM21.Service.Interface;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Localization;
using Microsoft.AspNetCore.Localization.Routing;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Options;
using Microsoft.OpenApi.Models;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using Serilog;
using Serilog.Events;
using Swashbuckle.AspNetCore.SwaggerUI;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using FM21.Data.Repository.Interface;
using FM21.Service.Interface;
using FM21.Core.DTO;
namespace FM21.API.Extensions
{
public static class ServiceExtensions
{
public static void ConfigureCors(this IServiceCollection services)
{
services.AddCors(o => o.AddPolicy("CorsPolicy", policyBuilder =>
{
policyBuilder
.WithOrigins(ConfigurationConstants.AllowedOrigins).AllowCredentials()
//.AllowAnyOrigin()
.AllowAnyMethod()
.AllowAnyHeader();
}));
}
public static void ConfigureIISIntegration(this IServiceCollection services)
{
services.Configure<IISOptions>(options =>
{
options.AutomaticAuthentication = true;
});
}
public static void SetupAPIVersioning(this IServiceCollection services)
{
services.AddApiVersioning(options =>
{
options.ReportApiVersions = true;
options.AssumeDefaultVersionWhenUnspecified = true;
options.DefaultApiVersion = new ApiVersion(1, 0);
options.UseApiBehavior = true;
//options.ApiVersionReader = new HeaderApiVersionReader("version");
});
}
public static void ConfigureControllerAndJsonSettings(this IServiceCollection services)
{
services.AddControllers()
.AddNewtonsoftJson(options =>
{
options.SerializerSettings.Converters.Add(new StringEnumConverter());
options.SerializerSettings.ContractResolver = new DefaultContractResolver();
options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
})
.AddJsonOptions(options =>
{
options.JsonSerializerOptions.PropertyNameCaseInsensitive = true;
});
}
public static void ConfigureDBContext(this IServiceCollection services, IConfiguration config)
{
services.AddDbContext<AppEntities>(options => options.UseSqlServer(ConfigurationConstants.DbConnectionString));
}
public static void ConfigureRepositoryAndServices(this IServiceCollection services)
{
services.AddSingleton<IActionContextAccessor, ActionContextAccessor>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
services.AddScoped<IUnitOfWork, UnitOfWork>();
services.AddScoped<IDatabaseFactory, DatabaseFactory>();
//services.AddScoped<ICacheProvider, CacheProvider>();
services.Add(new ServiceDescriptor(typeof(IRepository<>), typeof(Repository<>), ServiceLifetime.Scoped));
//services.AddScoped<IWebWorker, WebWorker>();
services.AddSingleton<IExceptionHandler, ExceptionHandler>();
#region Repository
services.AddScoped<ICustomerRepository, CustomerRepository>();
services.AddScoped<IIngredientMasterRepository, IngredientMasterRepository>();
services.AddScoped<IBrokerRepository, BrokerRepository>();
services.AddScoped<ISupplierMasterRepository, SupplierMasterRepository>();
services.AddScoped<ISiteRepository, SiteRepository>();
services.AddScoped<IIngridentCategoryRepository, IngridentCategoryRepository>();
services.AddScoped<IIngredientNutrientRepository, IngredientNutrientRepository>();
#endregion
#region Services
services.AddScoped<ICustomerService, CustomerService>();
services.AddScoped<IIngredientService, IngredientMasterService>();
services.AddScoped<ICommonService, CommonService>();
services.AddScoped<ISupplierMasterService, SupplierMasterService>();
services.AddScoped<ISiteService, SiteService>();
services.AddScoped<IIngredientCategoryService, IngredientCategoryService>();
services.AddScoped<IAllergenService, AllergenMasterService>();
services.AddScoped<IUserMasterService, UserMasterService>();
services.AddScoped<IRoleService, RoleService>();
services.AddScoped<IPermissionService, PermissionService>();
#endregion
#region Validator
//services.AddSingleton<IValidator<RoleMasterModel>, RoleMasterValidator>();
//services.AddSingleton<IValidator<PermissionMasterModel>, PermissionMasterValidator>();
//services.AddSingleton<IValidator<InstructionMasterModel>, InstructionMasterValidator>();
//services.AddSingleton<IValidator<InstructionGroupMasterModel>, InstructionGroupMasterValidator>();
//services.AddSingleton<IValidator<CustomerModel>, CustomerValidator>();
services.AddSingleton<IValidator<CustomerModel>, CustomerValidator>();
services.AddSingleton<IValidator<IngredientMasterModel>, IngredientValidator>();
services.AddSingleton<IValidator<SiteModel>, SiteValidator>();
services.AddSingleton<IValidator<IngridentCategoryModel>, IngridentCategoryValidator>();
//services.AddSingleton<IValidator<RegulatoryModel>, RegulatoryMasterValidator>();
//services.AddSingleton<IValidator<SupplierMasterModel>, SupplierMasterValidator>();
//services.AddSingleton<IValidator<AllergenMasterModel>, AllergenMasterValidator>();
#endregion
}
public static void ConfigureLoggerService(IConfiguration configuration)
{
Log.Logger = new LoggerConfiguration()
.Filter.ByExcluding(_ => !ConfigurationConstants.EnableLog)
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.File(
ConfigurationConstants.LogFilePath,
fileSizeLimitBytes: 1_000_000,
rollingInterval: RollingInterval.Day,
rollOnFileSizeLimit: true,
shared: true,
flushToDiskInterval: TimeSpan.FromSeconds(1)
)
.CreateLogger();
}
public static void ConfigureLocalization(this IServiceCollection services)
{
services.AddSingleton<IdentityLocalizationService>();
services.AddLocalization(o =>
{
// We will put our translations in a folder called Resources
o.ResourcesPath = "Resources";
});
services.AddSingleton<IStringLocalizerFactory, JsonStringLocalizerFactory>();
services.AddSingleton<IStringLocalizer, JsonStringLocalizer>();
services.AddMvc()
.AddViewLocalization(LanguageViewLocationExpanderFormat.Suffix, opts => { opts.ResourcesPath = "Resources"; })
.AddDataAnnotationsLocalization(options => { });
CultureInfo.CurrentCulture = new CultureInfo("en-US");
}
public static void AddLocalization(this IApplicationBuilder app)
{
IList<CultureInfo> supportedCultures = new List<CultureInfo>();
foreach (var item in ConfigurationConstants.SupportedLocalization.Split(","))
{
supportedCultures.Add(new CultureInfo(item));
}
var localizationOptions = new RequestLocalizationOptions
{
DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US"),
SupportedCultures = supportedCultures,
SupportedUICultures = supportedCultures
};
app.UseRequestLocalization(localizationOptions);
var requestProvider = new RouteDataRequestCultureProvider();
localizationOptions.RequestCultureProviders.Insert(0, requestProvider);
var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);
}
public static void ConfigureSwagger(this IServiceCollection services)
{
Dictionary<string, string> SwaggerPolicies = new Dictionary<string, string> { };
services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo { Title = "FM21 API", Version = "v1" });
//c.OperationFilter<SwaggerCultureFilter>();
//c.SchemaFilter<SwaggerExcludeFilters>();
//c.SchemaFilter<SwaggerNotNullableFilter>();
//c.SchemaFilter<AutoRestSchemaFilter>();
//c.DocumentFilter<SwaggerSecurityTrimming>();
c.EnableAnnotations();
c.DescribeAllEnumsAsStrings();
c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
{
In = ParameterLocation.Header,
Description = "Please insert token with Bearer into field",
Name = "Authorization",
Type = SecuritySchemeType.ApiKey
});
c.AddSecurityRequirement(new OpenApiSecurityRequirement
{
{
new OpenApiSecurityScheme
{
Reference = new OpenApiReference{Type = ReferenceType.SecurityScheme,Id = "Bearer"}
},
SwaggerPolicies?.Keys.ToArray()
}
});
var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml";
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);
if (File.Exists(xmlPath))
{
c.IncludeXmlComments(xmlPath);
}
});
}
public static void AddSwagger(this IApplicationBuilder app, IWebHostEnvironment env)
{
app.UseSwagger(c =>
{
c.RouteTemplate = "/swagger/{documentName}/swagger.json";
});
app.UseSwaggerUI(c =>
{
//c.RoutePrefix = "api";
c.DocumentTitle = $"FM21 API: {env?.EnvironmentName}";
c.SwaggerEndpoint("/swagger/v1/swagger.json", "FM21 API v1");
//string swaggerJsonBasePath = string.IsNullOrWhiteSpace(c.RoutePrefix) ? "." : "..";
//c.SwaggerEndpoint($"{swaggerJsonBasePath}/swagger/v1/swagger.json", "FM21 Api v1");
//c.DocumentTitle = $"App Api: {env?.EnvironmentName}";
//c.SwaggerEndpoint($"../swagger/v1/swagger.json", "FM21 Api v1");
// c.SwaggerEndpoint("/swagger/v1/swagger.json", "FM21 Api v1");
c.DefaultModelExpandDepth(2);
//c.DefaultModelRendering(ModelRendering.Example); ../
//c.DefaultModelsExpandDepth(-1);
//c.DisplayRequestDuration();
c.DocExpansion(DocExpansion.None);
c.EnableFilter();
//c.ShowExtensions();
c.EnableValidator();
});
}
}
}