您需要爲此使用動作過濾器。您可以擴展AuthorizeAttribute這樣的:
public class MyAuthorizeAttribute : AuthorizeAttribute
{
private UnitOfWork _unitOfWork = new UnitOfWork();
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
var isAuthorized = false;
var username = httpContext.User.Identity.Name;
// Some code to find the user in the database...
var user = _unitOfWork.UserRepository.Find(username);
if(user != null)
{
isAuthorized = true;
}
return isAuthorized;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
if (filterContext == null)
{
throw new ArgumentNullException("filterContext");
}
if (AuthorizeCore(filterContext.HttpContext))
{
SetCachePolicy(filterContext);
}
else
{
// If not authorized, redirect to the Login action
// of the Account controller...
filterContext.Result = new RedirectToRouteResult(
new System.Web.Routing.RouteValueDictionary {
{"controller", "Account"}, {"action", "Login"}
}
);
}
}
protected void SetCachePolicy(AuthorizationContext filterContext)
{
// ** IMPORTANT **
// Since we're performing authorization at the action level,
// the authorization code runs after the output caching module.
// In the worst case this could allow an authorized user
// to cause the page to be cached, then an unauthorized user would later
// be served the cached page. We work around this by telling proxies not to
// cache the sensitive page, then we hook our custom authorization code into
// the caching mechanism so that we have the final say on whether a page
// should be served from the cache.
HttpCachePolicyBase cachePolicy = filterContext.HttpContext.Response.Cache;
cachePolicy.SetProxyMaxAge(new TimeSpan(0));
cachePolicy.AddValidationCallback(CacheValidationHandler, null /* data */);
}
public void CacheValidationHandler(HttpContext context,
object data,
ref HttpValidationStatus validationStatus)
{
validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
}
}
然後,您可以在控制器級別或操作級別這樣使用這個屬性:
[MyAuthorize]
public ActionResult SomeAction()
{
// Code that is supposed to be accessed by authorized users only
}
我喜歡這個解決辦法,但我仍然得到401錯誤控制器方法應該允許任何人。在這種特殊情況下,我從C#'HttpWebRequest.GetResponse()'調用它來調用它。 'DebugController.FlushCaches()'具有[AllowAnonymous],並且在'web.config'中,我有一個' users>「的'Debug/FlushCaches'的標籤''。但是,當我'HttpWebRequest'調用它,我得到一個401 –
Pete
使用此爲您標籤: '<位置路徑= 「調試/ FlushCaches」> <授權> <允許用戶= 「*」/ > 授權> ' –
ataravati
http://stackoverflow.com/questions/15087755/use-anonymous-authentication-in-mvc4-on-single-controller-when-the-whole-applica – ataravati