User.GetUserId()在控制器的构造函数中失败 [英] User.GetUserId() fails inside controller's constructor

查看:156
本文介绍了User.GetUserId()在控制器的构造函数中失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误:值不能为空.参数名称:主体

如何在控制器的构造函数中访问Identity(userId)?我只能通过将失败的调用包装在一个函数中来使它正常工作(下面都突出显示).

How can I access Identity (userId) inside the controller's constructor? I can only get it working by wrapping the failed call in a function (both highlighted below).

有什么需要注射的吗?

public class BaseController : Controller {
    protected readonly MylDbContext dbContext;
    protected readonly string userId;

    public BaseController(MylDbContext dbContext) {
        this.dbContext = dbContext;
        userId = User.GetUserId(); // fails here
    }

    public string GetUserId() {
        return User.GetUserId(); // works here
    }
}

推荐答案

如@Henk所述,控制器构造函数将在设置ActionContext之前执行,因此您将无法访问ContextRequestUser.您需要在请求的上下文中检索userId.

As @Henk mentioned, the controller constructor will be executed before the ActionContext has been set, so you won't have access to properties like Context, Request or User. You need to retrieve the userId within the context of a request.

您可以使用动作过滤器仍是MVC6管道的一部分(该过滤器还通过IAsyncActionFilter支持异步动作过滤器).

You could use the old-fashioned approach of the action filters which are still part of the MVC6 pipeline (Which also supports async action filters via IAsyncActionFilter).

由于要在控制器中设置属性,因此最简单的实现方法是通过覆盖控制器类中的OnActionExecuting方法.之所以有效,是因为您从 ,它已经实现了IActionFilter.

Since you want to set a property in your controller, the most simple way you could implement this is by overriding the OnActionExecuting method in your controller class. This works because you are inheriting from Controller, which already implements IActionFilter.

public override void OnActionExecuting(ActionExecutingContext context)
{
    //Get user id   
    userId = User.GetUserId();
}

修改

如果您选中 DefaultControllerFactory 您将看到:

If you check the DefaultControllerFactory you will see that:

  1. 首先创建控制器
  2. 然后设置ActionContext(通过

  1. first the controller is created
  2. then the ActionContext is set (Via the DefaultControllerPropertyActivator which is one of the property activators):

var controller = _controllerActivator.Create(actionContext, controllerType);
foreach (var propertyActivator in _propertyActivators)
{
    propertyActivator.Activate(actionContext, controller);
}

这篇关于User.GetUserId()在控制器的构造函数中失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆