Asp.net-Mvc

在 ASP.net MVC 中從 Authorize 中排除一些操作

  • April 27, 2020

我的控制器頂部有一個授權屬性,這意味著它包含我的所有操作。我想從該屬性中排除一些操作(匿名使用者可以使用這些操作)。是否可以?

[Authorize]
public class TestController : Controller
{
  public ActionResult Index()
  {
    ...
  }
  ...

  //available by anonymous
  public ActionResult Test()
  {
    ...
  }
}

您可以採用此部落格文章中概述的方法來創建AllowAnonymous屬性並將此屬性放置在您希望排除的操作上:

http://blogs.msdn.com/b/rickandy/archive/2011/05/02/securing-your-asp-net-mvc-3-application.aspx

從 MVC 4 開始,該AllowAnonymous屬性是 stock 並且可以根據需要應用。

[Authorize]屬性放在控制器上基本上是將其放在每個操作上的快捷方式,因此您的程式碼在邏輯上等效於

// No [Authorize] here
public class TestController : Controller
{
   [Authorize]
   public ActionResult Index()
   {
        // code here...
   }

   [Authorize]
   public ActionResult Test()
   {
        // code here...
   }
}

您可能會看到我的目標 - 從控制器中刪除屬性,並將其放在您想要限制的特定操作上:

// No [Authorize] here
public class TestController : Controller
{
   [Authorize]
   public ActionResult Index()
   {
        // code here...
   }

   // no [Authorize] here either, so anonymous users can access it...
   public ActionResult Test()
   {
        // code here...
   }
}

引用自:https://stackoverflow.com/questions/6689150