C# mvc5 - 检查用户是否在每个 Controller 方法中经过身份验证的简单方法

标签 c# asp.net-mvc-5

我有一个 Controller ,我只希望经过身份验证的用户能够访问它。我是否必须检查我的 Controller 中的每个方法以验证用户是否已通过身份验证,或者是否有另一种方法来处理这个问题?我可以改用注释来执行此操作吗?

来 self 的 Controller 的示例:

public ActionResult Index()
        {
            if (UserVerified())
            {
               ...
            }
            return RedirectToAction("Login", "Account");
        }

    public ActionResult FacebookLogin()
    {
        if (UserVerified())
        {
           ....
        }

        return RedirectToAction("Login", "Account");
    }

    private bool UserVerified()
    {
        if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
        {
            return true;
        }
        return false;
    }

最佳答案

你可以为它使用 AuthorizeAttribute。
把它付诸行动。

[Authorize]
public ActionResult Index()
{
}

[Authorize]
public ActionResult FacebookLogin()
{
}

它将为您完成所有工作。它检查当前用户是否已通过身份验证。如果他通过了身份验证 - 继续执行操作,如果他没有通过身份验证 - 返回主页。

您还可以将此属性添加到 Controller 。然后所有操作都需要授权。

[Authorize]
public class HomeController
{
    public ActionResult Index()
    {
    }

    public ActionResult FacebookLogin()
    {
    }
}

更新:是的,正如 Kamil 所说。请阅读这篇文章。
http://www.asp.net/web-api/overview/security/authentication-and-authorization-in-aspnet-web-api

您现在花一些时间,将来花在 ASP.NET 身份验证问题上的时间会少得多。

顺便说一句,你不需要检查

User != null && User.Identity != null

如果您使用默认身份验证,那么您始终可以确定 User.Identity 是一个正确的对象。您可以直接访问 User.Identity.IsAuthenticated

关于C# mvc5 - 检查用户是否在每个 Controller 方法中经过身份验证的简单方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30658315/

相关文章:

c# - 在 javascript/razor 应用程序中按名称获取值

C# 获取 CPU 缓存未命中性能计数器

C# Access OleDb 标准表达式中的数据类型不匹配

c# - keycloak 不适用于 asp.net MVC5 web 应用程序 (C#)

c# - 旋转后在图像中找到原始点c#

c# - 为什么 ViewBag.SomeProperty 在属性不存在时不抛出异常?

asp.net-mvc-5 - 使用 Glass Mapper 的 Sitecore 8 可编辑字段

c# - 如何将 JSON 结果返回到 Ajax.BeginForm

c# - 在 Asp.net MVC 和 Web API 中实现审计跟踪的干净方法是什么

asp.net-mvc-5 - 如何在 MVC 5 中重写路由