Ali Mardini
Ali Mardini

Reputation: 350

Redirect in custom action filter

I am creating custom filter in asp.net MVC 5 and I am trying to redirect to a specific controller in the method On Action Executing I have tried Redirect To Action and its not work any suggestion? i am using this filter in web api controller here is my code :

public override void OnActionExecuting(HttpActionContext actionContext)
{
    Uri MyUrl = actionContext.Request.RequestUri;
    var host = MyUrl.Host;

    if (host == "localhost")
    {
       // redirect should be here
    }
}

Upvotes: 2

Views: 3246

Answers (2)

SᴇM
SᴇM

Reputation: 7213

For WebApi you can use HttpActionContext.Response Property:

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

Upvotes: 4

PSK
PSK

Reputation: 17943

If you are using MVC 5.2.3, you action filter should look like following.

 public class CustomActionFilter : ActionFilterAttribute, IActionFilter
    {
        void IActionFilter.OnActionExecuting(ActionExecutingContext filterContext)
        {

        }
    }

For redirection to a action, you can use code like following.

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

Upvotes: 4

Related Questions