在ASP.NET MVC中,将控制器用作ViewModel的构造函数中的参数是否有风险 [英] In ASP.NET MVC, is it risky to use the controller as an argument in the constructor for a ViewModel

查看:76
本文介绍了在ASP.NET MVC中,将控制器用作ViewModel的构造函数中的参数是否有风险的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,在我的所有页面上,我需要知道用户是否已登录并且(如果是)用户名。



为方便起见,我已经包含System.Web.Mvc并将构造函数中的Controller传递给我的基类PageViewModel,以便我可以根据控制器设置模型的UserIsLoggedIn和LoggedInUsername。我没有在ViewModel中维护对控制器的引用,因此它只在构造函数中使用。



这是一种常见做法吗?如果没有,你如何从控制器的上下文填写您的视图模型?

In my application, on all my pages, I need to know if the user is logged in and (if so) the username.

For convenience, I have been including System.Web.Mvc and passing in the Controller in the constructor to my base class of PageViewModel so that I can set the model's UserIsLoggedIn and LoggedInUsername based on the controller. I do not maintain a reference to the controller in the ViewModel, so it is only used in the constructor.

Is this a common practice? If not, how do you fill in your view model from the controller's context?

推荐答案

要查找用户是否已登录,您无需通过控制器。



根据您在应用程序中的位置,您可以使用HttpContext.Current.User找到它。



具体尝试使用HttpContext.Current.User.Identity.IsAuthenticated检查他们是否已登录。



并使用HttpContext.Current.User。 Identity.Name获取用户名



当你说Pages时我假设你的意思是...视图中已经有User对象可用,你可以只需说@ User.Identity.IsAuthenticated或@ User.Identity.Name
To find if the user is logged in, you don't need to pass the controller around.

Depending on where you are in the app you could use HttpContext.Current.User to find that out.

Specifically try using HttpContext.Current.User.Identity.IsAuthenticated to check if they are logged in.

And use HttpContext.Current.User.Identity.Name to get their username

And when you say "Pages" i assume you mean views ... the User object is already available in the view, you can simply say @User.Identity.IsAuthenticated or @User.Identity.Name


这篇关于在ASP.NET MVC中,将控制器用作ViewModel的构造函数中的参数是否有风险的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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