我正在尝试构建自定义AuthorizeAttribute,所以在我的Core项目(类库)中我有这样的代码:
using System;
using System.Web;
using System.Web.Mvc;
using IVC.Core.Web;
using System.Linq;
namespace IVC.Core.Attributes
{
public class TimeShareAuthorizeAttribute : AuthorizeAttribute
{
protected override bool AuthorizeCore(HttpContextBase httpContext)
{
if(!httpContext.Request.IsAuthenticated)
return false;
var rolesProvider = System.Web.Security.Roles.Providers["TimeShareRoleProvider"];
string[] roles = rolesProvider.GetRolesForUser(httpContext.User.Identity.Name);
if(roles.Contains(Website.Roles.RegisteredClient, StringComparer.OrdinalIgnoreCase))
{
return true;
}
return false;
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
filterContext.Result = new RedirectResult("/TimeShare/Account/LogOn");
base.HandleUnauthorizedRequest(filterContext);
}
}
}
当我尝试构建该东西时,我收到此错误: 错误2'IVC.Core.Attributes.TimeShareAuthorizeAttribute.AuthorizeCore(System.Web.HttpContextBase)':找不到合适的方法来覆盖 ......
我在这里遗漏了什么吗?我已经搜索了所有网站,但我找到的每个网站都告诉我要完成我在这里所做的事情。我正在使用mvc2 btw。
答案 0 :(得分:30)
是的,我也偶然发现了那个,并从对象浏览器中弄清楚了。除非你一直向下滚动到HttpContextBase类的用户注释,否则从MSDN文档中肯定不清楚。当然,网上有很多例子,但是没有人能够显示完整的类文件! :)
尝试将对System.Web.Abstractions的引用添加到项目中。
更新:刚从MSDN注意到在v3.5下,它在System.Web.Abstractions下,但在v4下,它在System.Web下。
答案 1 :(得分:23)
这是AuthorizationAttribute.cs
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
* This software is subject to the Microsoft Public License (Ms-PL).
* A copy of the license can be found in the license.htm file included
* in this distribution.
*
* You must not remove this notice, or any other, from this software.
*
* ***************************************************************************/
namespace System.Web.Mvc {
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
[SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes",
Justification = "Unsealed so that subclassed types can set properties in the default constructor or override our behavior.")]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class AuthorizeAttribute : FilterAttribute, IAuthorizationFilter {
private string _roles;
private string[] _rolesSplit = new string[0];
private string _users;
private string[] _usersSplit = new string[0];
public string Roles {
get {
return _roles ?? String.Empty;
}
set {
_roles = value;
_rolesSplit = SplitString(value);
}
}
public string Users {
get {
return _users ?? String.Empty;
}
set {
_users = value;
_usersSplit = SplitString(value);
}
}
// This method must be thread-safe since it is called by the thread-safe OnCacheAuthorization() method.
protected virtual bool AuthorizeCore(HttpContextBase httpContext) {
if (httpContext == null) {
throw new ArgumentNullException("httpContext");
}
IPrincipal user = httpContext.User;
if (!user.Identity.IsAuthenticated) {
return false;
}
if (_usersSplit.Length > 0 && !_usersSplit.Contains(user.Identity.Name, StringComparer.OrdinalIgnoreCase)) {
return false;
}
if (_rolesSplit.Length > 0 && !_rolesSplit.Any(user.IsInRole)) {
return false;
}
return true;
}
private void CacheValidateHandler(HttpContext context, object data, ref HttpValidationStatus validationStatus) {
validationStatus = OnCacheAuthorization(new HttpContextWrapper(context));
}
public virtual void OnAuthorization(AuthorizationContext filterContext) {
if (filterContext == null) {
throw new ArgumentNullException("filterContext");
}
if (AuthorizeCore(filterContext.HttpContext)) {
// ** 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(CacheValidateHandler, null /* data */);
}
else {
// auth failed, redirect to login page
filterContext.Result = new HttpUnauthorizedResult();
}
}
// This method must be thread-safe since it is called by the caching module.
protected virtual HttpValidationStatus OnCacheAuthorization(HttpContextBase httpContext) {
if (httpContext == null) {
throw new ArgumentNullException("httpContext");
}
bool isAuthorized = AuthorizeCore(httpContext);
return (isAuthorized) ? HttpValidationStatus.Valid : HttpValidationStatus.IgnoreThisRequest;
}
internal static string[] SplitString(string original) {
if (String.IsNullOrEmpty(original)) {
return new string[0];
}
var split = from piece in original.Split(',')
let trimmed = piece.Trim()
where !String.IsNullOrEmpty(trimmed)
select trimmed;
return split.ToArray();
}
}
}
答案 2 :(得分:8)
此外,由于我之前已经看到过这种情况,因此请小心让Visual Studio自动添加使用。如果您没有注意,最终可能会添加System.Web.Http而不是System.Web.Mvc。
答案 3 :(得分:2)
当我将旧代码复制到我的新项目时,发生了同样的问题。
原来有2个AuthrizeAttributes。一个在System.Web.Mvc中,另一个在System.Web.Http中。 Mvc有一个AuthrizeCore,而Http没有。
您可能需要添加对System.Web.Mvc的引用以访问正确的引用。
答案 4 :(得分:2)
我也有这个错误。事实证明,Visual Studio默认添加到我的ActionFilter:
使用System.Web.Http;
即使我添加了System.Web.Mvc,我仍然遇到错误。注释掉System.Web.Http并且只是使用System.Web.Mvc似乎为我解决了这个问题。
希望这可以帮助别人!
答案 5 :(得分:1)
使用System.Web.Mvc
命名空间。
示例代码:
using System.Web.Mvc;
public class CustomAuthorize : AuthorizeAttribute
{
protected override bool AuthorizeCore(System.Web.HttpContextBase httpContext)
{
var service = new AuthService();
return service.GetCurrentUser() != null;
}
public override void OnAuthorization(AuthorizationContext filterContext)
{
base.OnAuthorization(filterContext);
}
protected override void HandleUnauthorizedRequest(AuthorizationContext filterContext)
{
base.HandleUnauthorizedRequest(filterContext);
}
}
答案 6 :(得分:0)
在fw v4.5下,它现在显然在System.Web.Mvc下。