我在控制器上有一個授權屬性,但我想在一個動作中關閉它。 我創建了我自己的授權篩選器,並將「匿名」添加到角色列表中。在我的過濾器中,如果Anonymous出現在角色列表中,則返回true。是否可以禁用MVC控制器中的一個操作的授權?
但是,它似乎沒有通過登錄頁面,就好像控制器授權是搶佔其他任何東西一樣。
我在控制器上有一個授權屬性,但我想在一個動作中關閉它。 我創建了我自己的授權篩選器,並將「匿名」添加到角色列表中。在我的過濾器中,如果Anonymous出現在角色列表中,則返回true。是否可以禁用MVC控制器中的一個操作的授權?
但是,它似乎沒有通過登錄頁面,就好像控制器授權是搶佔其他任何東西一樣。
您可以將[Authorize]
添加到控制器類,然後將[AllowAnonymous]
添加到您不希望被授權的單一操作。例如:
[Authorize]
public class AccountController : Controller
{
public ActionResult Profile()
{
return View();
}
[AllowAnonymous]
public ActionResult Login()
{
return View();
}
}
這隻適用於MVC4及更高版本,但它可以很好地工作 – Nathan 2013-02-27 11:28:39
不要在您不需要的操作方法上添加AuthorizationAttribute。
我的自定義屬性
public class AuthorizationFilterAttribute : AuthorizeAttribute
{
Some code...
}
我控制器
public class UserController : BaseController, IDisposable
{
[AuthorizationFilterAttribute]
public ActionResult UserList()
{
//Authorize attribute will call when this action is executed
}
public ActionResult AddUser()
{
//Authorize attribute will not call when this action is executed
}
}
我希望你有我點什麼,我想說你。
=================更新回答========================== ===================== 創建一個像下面這樣的屬性。
public sealed class AnonymousAttribute : Attribute { }
請將下面的代碼放在您的OnAuthorization方法中。
public override void OnAuthorization(AuthorizationContext filterContext) {
bool checkForAuthorization = filterContext.ActionDescriptor.IsDefined(typeof(AnonymousAttribute), true)
|| filterContext.ActionDescriptor.ControllerDescriptor.IsDefined(typeof(AnonymousAttribute), true);
if (!skipAuthorization) {
base.OnAuthorization(filterContext);
}
}
您可以創建自己的屬性版本。
有一個非常相似的問題,並且有一個相當不錯的答案,如何實現自己的屬性來處理這種情況。
Override Authorize Attribute in ASP.NET MVC
Btw。你也可以創建你的控制器,默認情況下會有授權。
基地
[Authorize]
public abstract class SecureControllerBase : Controller
{
}
使用
public class MyController : SecureControllerBase
{
}
屬性只需添加到您要篩選的操作,而不是在控制器類。通過不裝飾動作,只要控制器或其基控制器之一沒有獲得該屬性,它們就不會被過濾。
我想要規則的例外,所以打開控制器,關閉一個動作。 – jaffa 2012-03-14 10:58:45
我剛剛做了一個使用Azure ACS作爲聯合身份提供程序的解決方案,並且接受的答案對我無效。對於那些正在掙扎的人來說,我的解決方案是完全繞過所需的控制器/視圖的安全。
爲您需要繞過授權的操作創建新的Controller/Views。
並在網上。config添加以下內容:
<location path="TheNameOfTheControllerYouWantToBypass">
<system.web>
<authorization>
<allow users="*" />
</authorization>
</system.web>
</location>
'(1):'不知道我理解你,有些代碼會很好。 '(2):'您可以在操作方法上添加授權屬性。 – gideon 2012-03-06 09:54:31
您可以創建屬性的自己的版本。 http://stackoverflow.com/questions/746998/override-authorize-attribute-in-asp-net-mvc – Tx3 2012-03-06 10:08:16
哎,大家似乎都不理解你:)。我明白,但我想要一個解決方案,因爲我有同樣的問題。你在此期間找到了什麼? – 2012-12-10 12:03:09