ASP.NET MVC。检查用户从授权的JavaScript [英] ASP.NET MVC. Check if user is authorized from JavaScript
问题描述
我使用ASP.NET MVC框架3和表单验证。我知道,如何检查服务器端,如果用户被授权为一些行动(以 [授权]
),我知道如何操作或内部检查此预览( User.Identity.IsAuthenticated
或用户的其他成员)。
I'm using ASP.NET MVC Framework 3 and Forms Authentication. I know, how to check on servers side, if the user is authorized for some action (with [Authorize]
) and I know, how to check this within an action or a view (with User.Identity.IsAuthenticated
or other members of 'User').
我想要做的事 - 被定义一些JavaScript code,将不同的执行,如果用户被授权根据
What I'm trying to do - is to define some JavaScript code, that will be executed differently, depending if the user is authorized.
考虑在页面上这样的脚本:
Consider such script on the page:
<script>
function Foo(){
if(userAuthorized)
alert("You\'re in the system");
} else {
alert("You\'re not authorized");
}
<script>
功能美孚()
被一些事件触发,比如单击。我想有检查的能力,如果用户被授权,在客户端。
Function Foo()
is triggered by some event, say click. And I'd like to have an ability to check, if user is authorized, on clients side.
我想出了最好的解决方案是真正呈现鉴于全局变量的初始化。像这样的:
The best solution I've came up with is to actually render global variables initialization in view. Like this:
@if(User.Identity.IsAuthenticated)
{
<script>
var userAuthorized = true;
</script>
}
else
{
<script>
var userAuthorized = false;
</script>
}
不过,这并不在我看来,作为一个好方法。是否有其他方法吗?
先谢谢了。
But it doesn't seems to me as a good approach. Are there any other ways? Thanks in advance.
PS:这是一个可用性问题,当然我在服务器上做必要的检查
PS: This is a usability issue, of course I'm doing necessary checks on server.
推荐答案
我喜欢@盖比的评论的想法,虽然我不知道这是否是可行的,因为我没有对你的项目的全貌。
I like the idea in @Gaby's comment, though I am not sure whether that's doable since I don't have the whole picture on your project.
最起码你可以通过执行简化您的code ...
At the very least you can simplify your code by doing...
<script>
var userAuthorized = @User.Identity.IsAuthenticated.ToString().ToLower();
</script>
这篇关于ASP.NET MVC。检查用户从授权的JavaScript的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!