2010-04-01 65 views
2

如何在整個控制器上啓用身份驗證並僅對某些操作方法禁用。我想要所有資源的身份驗證。如果我寫這樣的東西:ASP .NET MVC保護所有資源

[Authorize] 
public class HomeController : BaseController 
{ 
    //This is public 
    [UnAuthorized] 
    public ActionResult Index() 
    { 
     ViewData["Message"] = "Welcome to ASP.NET MVC!"; 
     return View(); 
    } 
    //This is private resource 
    public ActionResult PrivateResource() 
    { 
     return View(); 
    } 
} 

然後任何人都可以訪問此資源。我需要這個,因爲我們所有的資源都是私人的,而且我們的項目上很少公開。你有什麼想法如何使它更好的方式?

+0

Duplicate請參閱http://stackoverflow.com/questions/2071235/overriding-controller-authorizeattribute-for-just-one-action和http://stackoverflow.com/questions/2537307/asp-net-mvc-can -i-say-authorize-rolesadministrators-on-the-controller-class – 2010-04-01 09:30:14

+0

不,這不是我的問題的答案 – wassertim 2010-04-01 11:01:04

回答

1

基於解決方案被發現here我寫了修復正是我想要的代碼。

上創建自定義的AuthorizeAttribute授權屬性基地和覆蓋方法OnAuthorization:

public override void OnAuthorization(AuthorizationContext filterContext) 
    { 
     if (filterContext != null) 
     { 
      object[] attributes = filterContext.ActionDescriptor.GetCustomAttributes(false); 
      if (attributes != null) 
      { 
       foreach (var attribute in attributes) 
        if (attribute is UnAuthorizedAttribute) 
         return; 
      } 
     } 
     base.OnAuthorization(filterContext); 
    } 

我使用的是反射在這裏認識到未經授權的屬性的作用。我不知道這種情況下的性能問題,但它完全解決了這個問題。

+0

許多此代碼是不必要的。只需直接使用ActionDescriptor.GetCustomAttributes(),這樣就可以繞過使用反射來猜測傳入方法是什麼。 – Levi 2010-04-01 16:55:41

3

相應地組織您的控制器。爲所有已認證的資源設置一個基本控制器,您可以使用[Authorize]屬性註釋,另一個用於公共資源。

[Authorize] 
public abstract BaseAuthenticatedController : Controller 
{ } 

public abstract BaseController : Controller 
{ } 
+0

謝謝Darin。這不是我想要的。我希望能夠使控制器的某些操作方法公開,其餘部分是私有的。 – wassertim 2010-04-01 07:18:00