Search code examples
c#asp.net-web-apiactionfilterattribute

Redirect in a .NET API action filter


I'd like to be able to read a Request header in an ActionFilterAttribute, and direct the user. I'd also like to maintain the existing Request, or pass the controller and URL params to the new Request. I know this is easy in MVC, but haven't done it in a web API.


Solution

  • Actually it is very easy. You just create HttpResponseMessage object.

    public class RedirectAttribute : ActionFilterAttribute
        {
            public override void OnActionExecuting(HttpActionContext actionContext)
            {
                var response = actionContext.Request.CreateResponse(HttpStatusCode.Redirect);
                response.Headers.Location = new Uri("https://www.stackoverflow.com");
                actionContext.Response = response;
            }
        }