在ASP.NET MVC控制器授权和未授权用户分享行动 [英] Share Action with Authorized and Unauthorized User in ASP.NET MVC Controller

查看:296
本文介绍了在ASP.NET MVC控制器授权和未授权用户分享行动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个ASP.NET MVC应用程序,与控制器。所有在此控制器的操作都可以通过匿名用户访问。但是,如果用户进行身份验证,我想要做的事的行动特别。目前,我已经注意到,无论怎样,User.Identity.IsAuthenticated总是在这个动作的情况下错误的。这里是我的code:

I have an ASP.NET MVC app that with a controller. All of the actions in this controller can be accessed by anonymous users. However, if the user is authenticated, I want to do something special in the action. Currently, I've noticed that no matter what, User.Identity.IsAuthenticated is always false in the context of this action. Here is my code:

public class MyController : Controller
{
  public ActionResult GetProfile(string id)
  {
    if (User.Identity.IsAuthenticated) {
      ViewBag.ShowAuthStuff = true;
    } else {
      ViewBag.ShowAuthStuff = false;
    }
  }
}

我如何让它这样既通过身份验证和授权的用户可以访问相同的动作,但做不同的事情?我想不通为什么User.Identify.IsAuthenticated永远是假的。我检查了我的饼干。当我登录时,有一个名为cookie的:

How do I make it such that both an authenticated and an unauthenticated user can access the same action, but do different things? I can't figure out why User.Identify.IsAuthenticated is always false. I checked my cookies. When I'm logged in, there is a cookie named:

.ASPXAUTH

.ASPXAUTH

然而,当我访问的动作,该cookie不再可用。

However, when I visit the action, that cookie is no longer available.

推荐答案

只需使用这两种授权使用AllowAnonymous 过滤器

Just use both Authorize and AllowAnonymous filters:

[Authorize]
[AllowAnonymous]
public ActionResult GetProfile(string id)
{
    if (User.Identity.IsAuthenticated) {
        ViewBag.ShowAuthStuff = true;
    } else {
        ViewBag.ShowAuthStuff = false;
    }
}

虽然它没有一大堆的意义有一个配置文件匿名访问。

Though it doesn't make a whole lot of sense to have anonymous access to a "profile".

此外,通常情况下,你不想在同一个控制器混合授权和未授权的操作。最好是有一个单独的控制器必须或者可能需要在控制器授权一起行动,以及未经授权的操作。在这种情况下,您指定的控制器本身,然后使用AllowAnonymous 上希望任何个人行为上的授权过滤器与身份验证的用户交互,但并不需要它。

Also, typically, you don't want to mix authorized and unauthorized actions in the same controller. It's better to have actions that must or may require authorization in a controller together, and unauthorized actions in a separate controller. In that case, you specify the Authorize filter on the controller itself, and then AllowAnonymous on any individual actions that want to interact with authenticated users, but don't require it.

例如在帐户控制器:

[Authorize]
public class AccountsController : Controller
{
    public ActionResult Profile()
    {
        // Login required to reach here
    }

    [AllowAnonymous]
    public ActionResult Login()
    {
        if (User.Identity.IsAuthenticated)
        {
            // Already logged in, redirect to profile
            return RedirectToAction("Profile");
        }

        // Show login form for anonymous user
        return View()
    }
}

这篇关于在ASP.NET MVC控制器授权和未授权用户分享行动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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