Search code examples
c#asp.netentity-frameworkasp.net-corehttpcontext

error downloading username by IHttpContextAccessor after publication ASP.NET


I create applications for internal use,

trying to get user login through IHttpContextAccessor

Controller:

private Microsoft.AspNetCore.Http.IHttpContextAccessor _httpContextAccessor;

var userName = _httpContextAccessor.HttpContext.User.Identity.Name;


//var userName = @"ad\LOGINUSER";

if I extract username using _httpContextAccessor.HttpContext.User.Identity.Name; mam błąd na stronie

Error. An error occurred while processing your request. Request ID: |77762974-42ec74070b648c99.

Development Mode Swapping to Development environment will display more detailed information about the error that occurred.

if I use var userName = @"ad\LOGINUSER"; everything works normally

of course, the error is after publishing, everything works fine in normal compilation on computer

I'm using .net core 3.1

My startup code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using AppEcp.Models;
using Microsoft.EntityFrameworkCore;
using Newtonsoft.Json.Serialization;
using Microsoft.AspNetCore.Server.IISIntegration;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.AspNetCore.Mvc.Infrastructure;

namespace AppEcp

{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services
                .AddMvc();
            services
                .AddHttpContextAccessor();
         //   services
          //      .TryAddSingleton<IActionContextAccessor, ActionContextAccessor>();
            services
                .AddAuthentication(IISDefaults.AuthenticationScheme);
            services
                .AddControllersWithViews()
                .AddJsonOptions(options => options.JsonSerializerOptions.PropertyNamingPolicy = null);

            // .AddJsonOptions(options => options.SerializerSettings.ContractResolver = new DefaultContractResolver());
            services.AddCors(c =>
            {
                c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin());
            });


            var connectionAd = @"Server=wsql3;Database=ActiveDirectory;Trusted_Connection=True;MultipleActiveResultSets=true";
            services.AddDbContext<UzytkownicyDbContext>(options => options.UseSqlServer(connectionAd));

            var connectionUrlop = @"Server=wsql3;Database=ECP;Trusted_Connection=True;MultipleActiveResultSets=true";
            services.AddDbContext<EcpDbContext>(options => options.UseSqlServer(connectionUrlop));
        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
               // app.UseDatabaseErrorPage();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
               // app.UseHsts();
            }
          //  app.UseHttpsRedirection();
            app.UseStaticFiles();

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Ewidencja}/{id?}");
            });
        }
    }
}


does anyone know what i have done wrong?


Solution

    1. You didn't enable Authentication by UseAuthentication:

      app.UseAuthentication();  // add this line
      app.UseAuthorization();
      
    2. Within a Controller, you don't have to access HttpContext by _httpContextAccessor.HttpContext...., you can get the User by HttpContext.User.

    3. Also, it's your duty to check whether the User is null :

      var user = HttpContext.User;
      if(user ==null)
      {
          ...
      }else{
          var userName = user.Identity.Name;
          ...
      }
      

    Finally, if above changes doesn't fix the problem, could you please show us the logs?