gpt4 book ai didi

c# - 异常 : The given filter must implement one or more of the following filter interfaces when implementing custom filter in WebAPI 2

转载 作者:IT王子 更新时间:2023-10-29 04:46:23 36 4
gpt4 key购买 nike

我正在尝试构建我的自定义过滤器以进行身份​​验证,但是当我尝试运行我的 WebAPI 解决方案时遇到了这个问题:

The given filter instance must implement one or more of the following filter interfaces: System.Web.Mvc.IAuthorizationFilter, System.Web.Mvc.IActionFilter, System.Web.Mvc.IResultFilter, System.Web.Mvc.IExceptionFilter, System.Web.Mvc.Filters.IAuthenticationFilter.

错误发生在FilterConfig类:

public class FilterConfig
{
public static void RegisterGlobalFilters(GlobalFilterCollection filters)
{
filters.Add(new HandleErrorAttribute());
filters.Add(new AuthAttribute());
}
}

在我尝试将 AuthAttribute 添加到过滤器的行中。

这是整个 AuthAttribute 类:

using Examino.Business;
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.IdentityModel;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Web;
using System.Web.Http;
using System.Web.Http.Controllers;

namespace Examino.API.Filters
{
public class AuthAttribute : AuthorizeAttribute
{
public ITokenProviderService TokenProviderService { get; set; }

public override void OnAuthorization(HttpActionContext actionContext)
{
SetDependencies(actionContext);

if (!IsAuthorized(actionContext) && !SkipAuthorization(actionContext))
{
if (Authenticate(actionContext) == AuthenticationErrors.UNAUTHORIZED)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
new HttpResponseMessage(HttpStatusCode.Unauthorized));
}
else if (Authenticate(actionContext) == AuthenticationErrors.TOKEN_EXPIRED)
{
actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized,
//token expired status code?
new HttpResponseMessage(HttpStatusCode.Unauthorized));
}
}
}

private void SetDependencies(HttpActionContext actionContext)
{
var requestScope = actionContext.Request.GetDependencyScope();

if (TokenProviderService == null)
{
TokenProviderService = requestScope.GetService(typeof(ITokenProviderService)) as ITokenProviderService;
}
}

private AuthenticationErrors Authenticate(HttpActionContext actionContext)
{
IEnumerable<string> authHeaderValues;
actionContext.Request.Headers.TryGetValues("Authorization", out authHeaderValues);

try
{
if (authHeaderValues != null)
{
string bearerToken = authHeaderValues.ElementAt(0);
string token = bearerToken.StartsWith("Bearer ") ? bearerToken.Substring(7) : bearerToken;

Thread.CurrentPrincipal = TokenProviderService.ValidateJwtToken(token);
if (Thread.CurrentPrincipal != null)
{
return AuthenticationErrors.AUTHORIZED;
}
}
}
catch (SecurityTokenExpiredException)
{
return AuthenticationErrors.TOKEN_EXPIRED;
}
catch (Exception)
{
return AuthenticationErrors.UNAUTHORIZED;
}

return AuthenticationErrors.UNAUTHORIZED;
}

private bool SkipAuthorization(HttpActionContext actionContext)
{
Contract.Assert(actionContext != null);

return actionContext.ActionDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any()
|| actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes<AllowAnonymousAttribute>().Any();
}

private enum AuthenticationErrors
{
UNAUTHORIZED,
TOKEN_EXPIRED,
AUTHORIZED
}
}
}

如您所见,它继承自 AuthorizeAttribute 类。

这是堆栈跟踪:

[InvalidOperationException: The given filter instance must implement one or more of the following filter interfaces: System.Web.Mvc.IAuthorizationFilter, System.Web.Mvc.IActionFilter, System.Web.Mvc.IResultFilter, System.Web.Mvc.IExceptionFilter, System.Web.Mvc.Filters.IAuthenticationFilter.]
System.Web.Mvc.GlobalFilterCollection.ValidateFilterInstance(Object instance) +403
System.Web.Mvc.GlobalFilterCollection.AddInternal(Object filter, Nullable`1 order) +26
System.Web.Mvc.GlobalFilterCollection.Add(Object filter) +31
Examino.API.FilterConfig.RegisterGlobalFilters(GlobalFilterCollection filters) in C:\examino\src\Examino.API\App_Start\FilterConfig.cs:12
Examino.API.WebApiApplication.Application_Start() in C:\examino\src\Examino.API\Global.asax.cs:22

[HttpException (0x80004005): The given filter instance must implement one or more of the following filter interfaces: System.Web.Mvc.IAuthorizationFilter, System.Web.Mvc.IActionFilter, System.Web.Mvc.IResultFilter, System.Web.Mvc.IExceptionFilter, System.Web.Mvc.Filters.IAuthenticationFilter.]
System.Web.HttpApplicationFactory.EnsureAppStartCalledForIntegratedMode(HttpContext context, HttpApplication app) +540
System.Web.HttpApplication.RegisterEventSubscriptionsWithIIS(IntPtr appContext, HttpContext context, MethodInfo[] handlers) +186
System.Web.HttpApplication.InitSpecial(HttpApplicationState state, MethodInfo[] handlers, IntPtr appContext, HttpContext context) +172
System.Web.HttpApplicationFactory.GetSpecialApplicationInstance(IntPtr appContext, HttpContext context) +402
System.Web.Hosting.PipelineRuntime.InitializeApplication(IntPtr appContext) +343

[HttpException (0x80004005): The given filter instance must implement one or more of the following filter interfaces: System.Web.Mvc.IAuthorizationFilter, System.Web.Mvc.IActionFilter, System.Web.Mvc.IResultFilter, System.Web.Mvc.IExceptionFilter, System.Web.Mvc.Filters.IAuthenticationFilter.]
System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +539
System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +125 System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +731

即使我实现了例如 IAuthenticationFilter 接口(interface),无论如何也会抛出相同的异常。

有人遇到过类似的异常吗?我无法在 WebAPI 中找到更多相关信息。

最佳答案

已解决:问题是过滤器的注册位置。在 MVC 中,您将在 FilterConfing 类中注册过滤器,但在 WebAPI 中,您在 WebApiConfig 类的 Register 方法中执行此操作,如下所示:

config.Filters.Add(new AuthAttribute());

现在一切正常。

关于c# - 异常 : The given filter must implement one or more of the following filter interfaces when implementing custom filter in WebAPI 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39717227/

36 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com