2013-02-15 63 views
1

already asked類似的問題,但我想知道如果解決方案可以簡化。 正如你可能已經注意到,我想確保登錄的用戶只能訪問他的數據。我在mvc3中使用自定義成員資格提供程序。確保登錄的用戶只能訪問他的數據

[Authorize(Users=httpContext.User.Identity.Name)] 
public ActionResult UserArea() 
{} 

感謝

回答

0

創建一個新的屬性和覆蓋AuthorizeCore方法:

public class CustomAuthorizeAttribute : AuthorizeAttribute 
{ 
    protected override bool AuthorizeCore(HttpContext.User user) 
    { 
    // Generally authenticated to the site 
    if (!httpContext.User.Identity.IsAuthenticated) { 
     return false; 
    } 

    return true; 
    } 
} 

然後在你的控制器做:

[CustomAuthorize(httpContext.User] 
public ActionResult MyControllerAction() 
{ 
    return View(); 
} 

http://code.commongroove.com/2012/04/20/asp-net-mvc-simple-custom-authorization-by-inheriting-from-the-authorizeattribute/

相關問題