2
我試圖實現Phil Haack在他的一個節目中做的RequireLocalHostActionFilter。asp.net mvc RequireLocalHostActionFilter不開火
它的ActionFilter它會檢查給定方法的調用是否來自本地主機,並在全局過濾器中註冊。
但我的過濾器不工作,我不能讓我的頭靠近它。
因此,如果有人有空閒時間去看看,請。
我ActionFilter:
public class RequireLocalHostActionFilter : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
return !httpContext.Request.IsLocal; // I need to test on the local host, so I reverse the logic.
}
}
我FilterProvider
public class ConditionalFilterProvider : IFilterProvider
{
public readonly IEnumerable<Func<ControllerContext, ActionDescriptor, object>> _conditions;
public ConditionalFilterProvider(IEnumerable<Func<ControllerContext, ActionDescriptor, object>> conditions)
{
this._conditions = conditions;
}
public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
{
IEnumerable<Filter> result = from condition in _conditions
select condition(controllerContext, actionDescriptor)
into filter
where filter != null
select new Filter(filter, FilterScope.Global, null);
return result;
}
}
在全局變量。
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
var conditions = new Func<ControllerContext, ActionDescriptor, object>[]
{
(c, a) =>
a.ControllerDescriptor.ControllerName.Equals("Online", StringComparison.OrdinalIgnoreCase)
? null : new RequireLocalHostActionFilter()
};
filters.Add(new ConditionalFilterProvider(conditions));
filters.Add(new HandleErrorAttribute());
}
我可以看到動作過濾器被添加到過濾器集合中。 和最後我OnlineController,一個simpel控制,我想要的全局過濾一命嗚呼
public class OnlineController : Controller
{
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC! online";
return View();
}
// THX抽出寶貴的時間來閱讀這篇文章。 //丹尼斯