gpt4 book ai didi

c#-4.0 - 在我的基本 Controller 构造函数上获取用户身份

转载 作者:行者123 更新时间:2023-12-04 10:25:36 25 4
gpt4 key购买 nike

我在我的 ASP.NET MVC4 网站上有一个基本 Controller ,它有一个简单的构造函数:

public class BaseController : Controller
{
protected MyClass Foo { get; set; }
public BaseController()
{
if (User.Identity.IsAuthenticated))
{
Foo = new MyClass();
}
}
}

但是我无法访问 User这里。它是 null .但是在我继承的 上 Controller 没关系。

谢谢

最佳答案

Controller 实例化将在授权发生之前发生。即使您的 MVC 应用程序调用 RenderAction()好几次,你最终会创建五个不同的 Controller ,这五个 Controller 将在任何 OnAuthorization 之前创建。发生。

处理这些情况的最佳方法是使用 Action Filters . Authorize Attribute很早就被解雇了,很可能适合你的情况。

首先,让我们创建一个 授权过滤器 .

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
public class MyClassAuthorizationAttribute : Attribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext.HttpContext.User.Identity.IsAuthenticated)
{
filterContext.Controller.ViewData["MyClassInstance"] = new MyClass();
}
}
}

现在让我们更新我们的 Controller
[MyClassAuthorization]
public class BaseController : Controller
{
protected MyClass Foo
{
get { return (MyClass)ViewData["MyClassInstance"]; }
}
}

关于c#-4.0 - 在我的基本 Controller 构造函数上获取用户身份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19236064/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com