2013-03-03 102 views
0

我有一個mvc4內聯網網站,我正在開發的網頁前端只有幾個AD組可以訪問,但我也使用web API mvc4的功能和我需要向所有用戶開放,甚至是匿名用戶。我嘗試過使用Web.config,但阻止所有不在其中一個組中的用戶。只允許訪問組,但API全部

如何在保持API打開的同時保護前端?

更新:

我只是想,我想避免標記每個方法與屬性 像[Authorize]

+0

您使用.NET Membership嗎? – balexandre 2013-03-03 21:31:21

+0

不,它是一個Intranet應用程序,並且正在使用AD(活動目錄) – 2013-03-04 00:07:50

+0

您可以從[.NET成員身份甚至使用AD]中受益(http://msdn.microsoft.com/zh-cn/library/ff650308.aspx)!它會讓你的工作更好,更快! – balexandre 2013-03-04 06:51:57

回答

0

想通了。

我只是應用了一個過濾器來檢查每個控制器的命名空間。由於我所有的API控制器都在HSServer.Controllers.Api,而且所有的網絡控制器都在HSServer.Controllers.Web,所以我的FilterConfig.cs中的代碼就像一個魅力一樣。

public class FilterConfig 
{ 
    public static void RegisterGlobalFilters(GlobalFilterCollection filters) 
    { 
     filters.Add(new FrontendAuthorize()); 
     filters.Add(new HandleErrorAttribute()); 
    } 
} 

public class FrontendAuthorize : AuthorizeAttribute 
{ 
    public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     try 
     { 
      if (!filterContext.Controller.GetType().Namespace.StartsWith("HSServer.Controllers.Api")) 
       base.OnAuthorization(filterContext); 
     } 
     catch (NullReferenceException) 
     { 
      base.OnAuthorization(filterContext); 
     } 
    } 
}