Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redirect in custom action filter

Tags:

c#

asp.net-mvc

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
    }
}
like image 437
Ali Mardini Avatar asked Jan 25 '26 14:01

Ali Mardini


2 Answers

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;
 }
like image 100
SᴇM Avatar answered Jan 27 '26 02:01

SᴇM


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" }
                        });
like image 31
PSK Avatar answered Jan 27 '26 03:01

PSK



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!