问题描述
我创建了一个自定义的过滤器属性,该属性将进行一些基本的令牌验证.因此,我首先添加了几行以查看其是否正常工作,但是由于某种原因,它无法正常工作.
I have created a custom Filter Attribute that will be doing some basic token validation. So I started by just adding a few lines to see with it works correctly but for some reason is it not working.
自定义过滤器类
/// <summary>
/// Basic Token Based Authitication
/// </summary>
public class BasicTokenValidation : ActionFilterAttribute
{
/// <summary>
/// Validate Token
/// </summary>
/// <param name="actionContext"></param>
public override void OnActionExecuting(HttpActionContext actionContext)
{
HttpContext.Current.Response.Write(" filter1 ");
Debug.WriteLine("Executing My Filter!");
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized);
}
else {
string authToken = actionContext.Request.Headers.Authorization.Parameter;
}
base.OnActionExecuting(actionContext);
}
}
我在 WebApi.config
config.Filters.Add(new BasicTokenValidation());
这是我装饰控制器方法的方式
Here is how I decorated my Controller method
[HttpGet]
[Route("get/all")]
[BasicTokenValidation]
public IHttpActionResult GetAll()
{
try
{
// Some Code
}
catch (Exception ex)
{
return InternalServerError(ex);
}
}
不确定是否需要配置其他内容.确实阅读了一些帖子和文章,但对于某些人来说,我确实拥有创建自定义过滤器所需的一切.
Not sure if I need to configure something else. Did read a few post and articles and to some I do have everything what I need to create custom filters.
任何帮助将不胜感激.
谢谢
推荐答案
您的操作过滤器正在运行.您可以确保使用WebAPI程序集System.Web.Http.Filters
而不是MVC程序集System.Web.Http.Mvc
吗?
Your action filter is working. Could you ensure that you use WebAPI assembly System.Web.Http.Filters
instead of MVC assembly System.Web.Http.Mvc
?
using System.Diagnostics;
using System.Web;
using System.Web.Http.Controllers;
using System.Web.Http.Filters; <--- WebAPI assembly
namespace YOURNAMESPACE
{
public class BasicTokenValidation : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
HttpContext.Current.Response.Write(" filter1 ");
Debug.WriteLine("Executing My Filter!");
if (actionContext.Request.Headers.Authorization == null)
{
actionContext.Response =
new System.Net.Http.HttpResponseMessage(
System.Net.HttpStatusCode.Unauthorized);
}
else
{
string authToken = actionContext.Request.Headers.Authorization.Parameter;
}
base.OnActionExecuting(actionContext);
}
}
}
由于您在全局范围内 注册了BasicTokenValidation操作过滤器,因此您可能需要查看使用DelegatingHandler进行基本身份验证我用SO回答.
Since you register BasicTokenValidation action filter globally, you might want to look at Basic Authentication using DelegatingHandler that I answered in SO.
这篇关于Web API自定义过滤器未触发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!