【问题标题】:C# .Net Core ASP.Net API User Is NullC# .Net Core ASP.Net API 用户为空
【发布时间】:2018-05-31 08:12:35
【问题描述】:

我有一个基本的 C# 2.0 .Net Core API。在控制器内部,我调用 User.Identity 来获取登录用户的信息。我将 IdentityServer 4 与 Jwt Bearer 身份验证一起使用。问题是User 为空。然而在 NLog 输出中,它正确地找到了我的名字并说我已登录。我尝试发送错误的令牌,但它正确地拒绝了我。

017-12-14 11:21:57.6788||INFO|Microsoft.AspNetCore.Hosting.Internal.WebHost|Request starting HTTP/1.1 GET http://localhost:62150/api/v1/user   
    2017-12-14 11:21:58.9575||INFO|Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler|Successfully validated the token. 
    2017-12-14 11:21:58.9637||INFO|Microsoft.AspNetCore.Authentication.JwtBearer.JwtBearerHandler|AuthenticationScheme: BearerIdentityServerAuthenticationJwt was successfully authenticated. 
    2017-12-14 11:21:58.9637||INFO|IdentityServer4.AccessTokenValidation.IdentityServerAuthenticationHandler|AuthenticationScheme: Bearer was successfully authenticated. 
    2017-12-14 11:21:59.0217||INFO|Microsoft.AspNetCore.Authorization.DefaultAuthorizationService|Authorization was successful for user: Ken. 
    2017-12-14 11:21:59.1724||INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executing action method Controllers.UserController.Index with arguments ((null)) - ModelState is Valid 
    2017-12-14 11:22:01.7092||INFO|Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker|Executed action Controllers.UserController.Index in 2690.9354ms 
    2017-12-14 11:22:01.7548||ERROR|Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware|An unhandled exception has occurred while executing the request Object reference not set to an instance of an object.

[Route("api/v1/[controller]")]
    [Authorize]
    public class UserController : ApiController
    {
        /// <summary>
        /// GET /user
        /// </summary>
        /// <remarks>Get information about the current logged in user.  Required Authorization.</remarks>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> Index()
        {
            var identity = this.User.Identity.GetUserGuid();
        }
    }




// 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.UseCors("default");
            app.UseAuthentication();
            app.UseMvc();
        }

 // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvcCore()
                .AddAuthorization()
                .AddJsonFormatters();

            services.AddMemoryCache();

            services.AddCors(o => o.AddPolicy("default", builder =>
            {
                builder.AllowAnyOrigin()
                       .AllowAnyMethod()
                       .AllowAnyHeader();
            }));

            JwtSecurityTokenHandler.DefaultInboundClaimTypeMap.Clear();
            services.AddAuthentication(IdentityServerAuthenticationDefaults.AuthenticationScheme)
                .AddIdentityServerAuthentication(options =>
                {
                    options.Authority = "http://localhost:5000"; // Auth Server
                    options.RequireHttpsMetadata = false; // only for development
                    options.ApiName = "webApi"; // API Resource Id
                    options.SaveToken = true;
                });
        }

【问题讨论】:

  • 您有问题吗?
  • The issue is User is null.
  • 这不是问题。
  • 好的。 Why is User null?
  • 您是否被重定向到身份服务器进行身份验证?

标签: c# asp.net asp.net-web-api asp.net-core identityserver4


【解决方案1】:

问题是因为我调用的是 ApiController 而不是新的 Mvc BaseController。问题已解决。

【讨论】:

    【解决方案2】:

    您的控制器应该继承自控制器基类。

    【讨论】:

    • 这不是必需的。 ASP.NET Core 也支持 POCO 控制器
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-28
    • 2020-04-11
    • 1970-01-01
    • 2019-05-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多