Using MVC 4 and WebAPI, how do I redirect to an alternative service endpoint from a custom filter?

Thanks for watching.

This is a trivial task when using a normal (non-WebAPI) action filter, since I can simply change the filterContext.Result property as follows:

filterContext.Result = new RedirectToRouteResult( new RouteValueDictionary { { "controller", "Home" }, {"action", "Index" } }); 

Unfortunately, I have to use the HttpActionContext for the WebAPI, so I cannot access filterContext.Result .

So what should I do instead? I have a filter installed and it runs at the appropriate time, I just don’t know how to prevent its execution, and instead specify another one.

Here is my controller:

 [VerifyToken] public class ProductController : ApiController { #region Public public List<DAL.Product.CategoryModel> ProductCategories(GenericTokenModel req) { return HelperMethods.Cacheable(BLL.Product.GetProductCategories, "AllCategories"); } public string Error() //This is the endpoint I would like to reach from the filter! { return "Not Authorized"; } #endregion Public #region Models public class GenericTokenModel { public string Token { get; set; } } #endregion Models } 

Here is my filter:

 using System.Web.Http.Controllers; using ActionFilterAttribute = System.Web.Http.Filters.ActionFilterAttribute; namespace Web.Filters { public class VerifyTokenAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext filterContext) { dynamic test = filterContext.ActionArguments["req"]; if (test.Token != "foo") { //How do I redirect from here?? } base.OnActionExecuting(filterContext); } } } 

Any help is appreciated.

+4
source share
1 answer

In my case, the answer was simply to change the Response filterContext property, rather than redirecting to another endpoint. This achieved the desired result.

Here is the edited filter:

 public class VerifyTokenAttribute : ActionFilterAttribute { public override void OnActionExecuting(HttpActionContext filterContext) { dynamic test = filterContext.ActionArguments["req"]; if (test.Token != "foo") { filterContext.Response = new HttpResponseMessage(HttpStatusCode.Unauthorized); } base.OnActionExecuting(filterContext); } } 
+4
source

Source: https://habr.com/ru/post/1502929/


All Articles