ASP.NET Core - HttpContext.User.Identity.Name在控制器中为null

时间:2017-07-21 08:50:08

标签: c# asp.net asp.net-core authorization asp.net-core-mvc

我在ASP.NET Core中使用自定义CookieAuthentication,我在HomeController中有这三种方法:

[Authorize]
public class HomeController : Controller
{
    public async Task<IActionResult> Index()
    {
        _logger.LogInformation("Index()");
        if (HttpContext.User.Identity.Name != null)
        {
            _logger.LogInformation(User.Identity.Name);
        }
        ...
    }

    [HttpGet("getlastdisposal")]
    [AllowAnonymous]
    public JsonResult GetLastDisposal()
    {
        _logger.LogInformation("GetLastDisposal()");
        if (HttpContext.User.Identity.Name != null)
        {
            _logger.LogInformation(User.Identity.Name);
        }
        else
        {
            _logger.LogInformation("IT IS NULL");
        }
        ...
    }

    [HttpGet("getchartdata")]
    public JsonResult GetChartData()
    {
        ...
    }
}

我要回来的日志是:

...
info: Server.Controllers.HomeController[0]
      Index()
info: Server.Controllers.HomeController[0]
      admin
...
info: Server.Controllers.HomeController[0]
      GetLastDisposal()
info: Server.Controllers.HomeController[0]
      IT IS NULL
...
info: Microsoft.AspNetCore.Authorization.DefaultAuthorizationService[2]
      Authorization failed for user: (null).
info: Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker[1]
      Authorization failed for the request at filter 'Microsoft.AspNetCore.Mvc.Authorization.AuthorizeFilter'.
info: Microsoft.AspNetCore.Mvc.ChallengeResult[1]
      Executing ChallengeResult with authentication schemes ().
info: Microsoft.AspNetCore.Authentication.Cookies.CookieAuthenticationMiddleware[12]
      AuthenticationScheme: Cookies was challenged.

看一看,似乎HttpContext.User.Identity.Name在第一次成功授权后(Index()之前)变为空,这使得GetChartData()之前的授权失败。关于为什么会发生这种情况以及如何解决它的任何想法?

0 个答案:

没有答案