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.
Custom Filter Class
/// <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);
}
}
I registered it in 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.
Any assistance would be appreciated.
Thanks
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);
}
}
}
Since you register BasicTokenValidation action filter globally, you might want to look at Basic Authentication using DelegatingHandler that I answered in SO.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With