Search code examples
c#actionfilterattribute

ActionFilterAttribute on Web api call does not correctly redirect to the new location


My action filter attribute does not redirect to the new url i have defined:

public class RunOnServerAttribute : System.Web.Http.Filters.ActionFilterAttribute
{
    public ServerType Type;

    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext filterContext)
    {
        switch (Type)
        {
            case ServerType.CMS:
                if (!filterContext.Request.RequestUri.AbsoluteUri.StartsWith(Config.CMSUrl))
                {
                    Uri correctedUri = new Uri($"{Config.CMSUrl.TrimEnd('/')}/{filterContext.Request.RequestUri.PathAndQuery.TrimStart('/')}");
                    var response = filterContext.Request.CreateResponse(System.Net.HttpStatusCode.Moved);
                    response.Headers.Location = correctedUri;
                    return;
                    // This does not seem to work
                }

                break;
        }

        base.OnActionExecuting(filterContext);
    }
}

It just continues on with the normal request. I am debugging this by inspecting the Request.RequestUri in the executing api method


Solution

  • Sorry for not noticing it's a WebAPI project. Composing the response should be a quick resolution.

    var res = actionContext.Request.CreateResponse(HttpStatusCode.Redirect);
    res.Headers.Location = new Uri("https://www.google.com");
    actionContext.Response = res;
    

    ------------- Updated above. --------------

    You should use the filterContext.Result and assign the ActionResult. Just like what you do in normal actions. For instance,

    var controller = (YourBaseControllerType)filterContext.Controller;
    filterContext.Result = controller.RedirectToAction("actionName", "controllerName");
    

    or

    filterContext.Result = new RedirectResult(YourUrl);