2013-03-03 118 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); 
     } 
    } 
}