[英]ASP.Net MVC 3: Inverse Authorize Attribute
我有一個簡單的ASP.Net MVC 3應用程序,它有一些控制器和一些很好的操作。
現在,由於這是基於用戶的應用程序,因此大多數控制器操作都需要對用戶進行身份驗證。 MVC使用內置的Authorize屬性處理這個問題,您可以使用該屬性單獨裝飾控制器和/或操作。
最棒的是你可以將屬性應用於控制器,並且給定控制器的所有操作也將應用它 - 保存了大量的輸入;)
但我有一個控制器,比方說,10個動作。 但我希望其中一個操作沒有應用Authorize屬性。
是的,我可以將該屬性應用於其他9並將其從控制器中刪除,這將完全符合我的需要。 但有沒有辦法將它應用於控制器,只是選擇排除其中一個動作?
實際上,會想要......
[!Authorize]
或[NotAuthorize]
我知道我可以創建一個可以完成這項工作的自定義工具,但我想知道的是,是否有內置方法可以做到這一點? 或者我是否必須將該屬性應用於所有其他9個其他操作?
請注意,ASP.NET MVC 4.0中添加了一個新屬性,它正是這樣做的:
[使用AllowAnonymous]
Phil Haack最近寫了一篇關於這個確切場景的博客文章:
他的解決方案包括編寫一個自定義的“條件過濾器提供程序”,允許用戶為操作方法的屬性指定過濾條件。
細節和推理在他的帖子中,但代碼相對簡單。 首先,創建過濾器提供程序:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
public class ConditionalFilterProvider : IFilterProvider {
private readonly
IEnumerable<Func<ControllerContext, ActionDescriptor, object>> _conditions;
public ConditionalFilterProvider(
IEnumerable<Func<ControllerContext, ActionDescriptor, object>> conditions)
{
_conditions = conditions;
}
public IEnumerable<Filter> GetFilters(
ControllerContext controllerContext,
ActionDescriptor actionDescriptor) {
return from condition in _conditions
select condition(controllerContext, actionDescriptor) into filter
where filter != null
select new Filter(filter, FilterScope.Global, null);
}
}
然后應用它:
IEnumerable<Func<ControllerContext, ActionDescriptor, object>> conditions =
new Func<ControllerContext, ActionDescriptor, object>[] {
(c, a) => c.Controller.GetType() != typeof(HomeController) ?
new MyFilter() : null,
(c, a) => a.ActionName.StartsWith("About") ? new SomeFilter() : null
};
var provider = new ConditionalFilterProvider(conditions);
FilterProviders.Providers.Add(provider);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.