Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/asp.net/32.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 发布ASP.NET后,IHttpContextAccessor下载用户名时出错_C#_Asp.net_Entity Framework_Asp.net Core_Httpcontext - Fatal编程技术网

C# 发布ASP.NET后,IHttpContextAccessor下载用户名时出错

C# 发布ASP.NET后,IHttpContextAccessor下载用户名时出错,c#,asp.net,entity-framework,asp.net-core,httpcontext,C#,Asp.net,Entity Framework,Asp.net Core,Httpcontext,我创建应用程序供内部使用 试图通过IHttpContextAccessor获取用户登录 控制器: private Microsoft.AspNetCore.Http.IHttpContextAccessor _httpContextAccessor; var userName = _httpContextAccessor.HttpContext.User.Identity.Name; //var userName = @"ad\LOGINUSER"; 如果我使用_httpContextA

我创建应用程序供内部使用

试图通过IHttpContextAccessor获取用户登录

控制器:

private Microsoft.AspNetCore.Http.IHttpContextAccessor _httpContextAccessor;

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


//var userName = @"ad\LOGINUSER";
如果我使用_httpContextAccessor.HttpContext.User.Identity.Name提取用户名;błd na stronie妈妈

错误。 处理您的请求时出错。 请求ID:| 77762974-42ec74070b648c99

发展模式 切换到开发环境将显示有关所发生错误的更详细信息

如果我使用var userName=@“ad\LOGINUSER”;一切正常

当然,错误是在发布之后,在计算机上进行正常编译时一切正常

我正在使用.NETCore3.1

我的启动代码

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?}");
            });
        }
    }
}


使用系统;
使用System.Collections.Generic;
使用System.Linq;
使用System.Threading.Tasks;
使用Microsoft.AspNetCore.Builder;
使用Microsoft.AspNetCore.Hosting;
使用Microsoft.AspNetCore.HttpsPolicy;
使用Microsoft.Extensions.Configuration;
使用Microsoft.Extensions.DependencyInjection;
使用Microsoft.Extensions.Hosting;
使用AppEcp.模型;
使用Microsoft.EntityFrameworkCore;
使用Newtonsoft.Json.Serialization;
使用Microsoft.AspNetCore.Server.IISIntegration;
使用Microsoft.Extensions.DependencyInjection.Extensions;
使用Microsoft.AspNetCore.Mvc.Infrastructure;
名称空间AppEcp
{
公营创业
{
公共启动(IConfiguration配置)
{
配置=配置;
}
公共IConfiguration配置{get;}
//此方法由运行时调用。请使用此方法将服务添加到容器中。
public void配置服务(IServiceCollection服务)
{
服务
.AddMvc();
服务
.AddHttpContextAccessor();
//服务
//.TryAddSingleton();
服务
.AddAuthentication(IISDefaults.AuthenticationScheme);
服务
.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(options=>options.UseSqlServer(connectionAd));
var connectionUrlop=@“服务器=wsql3;数据库=ECP;可信连接=True;MultipleActiveResultSets=True”;
services.AddDbContext(options=>options.UseSqlServer(connectionUrlop));
}
//此方法由运行时调用。请使用此方法配置HTTP请求管道。
public void配置(IApplicationBuilder应用程序、IWebHostEnvironment环境)
{
if(env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
//app.UseDatabaseErrorPage();
}
其他的
{
app.UseExceptionHandler(“/Home/Error”);
//app.UseHsts();
}
//app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.UseAuthorization();
app.UseEndpoints(端点=>
{
endpoints.MapControllerRoute(
名称:“默认”,
模式:“{controller=Home}/{action=Ewidencja}/{id?}”);
});
}
}
}
有人知道我做错了什么吗

  • 您没有通过
    UseAuthentication
    启用
    Authentication

    app.UseAuthentication();  // add this line
    app.UseAuthorization();
    
  • 在控制器中,您不必通过
    访问HttpContext\u httpContextAccessor.HttpContext….
    ,您可以通过
    HttpContext.User
    获取用户

  • 此外,您有责任检查用户是否为空:

    var user = HttpContext.User;
    if(user ==null)
    {
        ...
    }else{
        var userName = user.Identity.Name;
        ...
    }
    
  • 最后,如果上述更改无法解决问题,请向我们展示日志