【问题标题】:Redirect in custom action filter在自定义操作过滤器中重定向
【发布时间】:2018-05-08 05:21:31
【问题描述】:

我正在 asp.net MVC 5 中创建自定义过滤器,我试图在 On Action Executing 方法中重定向到特定控制器我已经尝试过 Redirect To Action 并且它没有任何建议? 我在 web api 控制器中使用这个过滤器 这是我的代码:

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

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

【问题讨论】:

  • 代码在哪里?
  • its not work 这是什么意思?您需要分享代码并告诉我们您在哪里使用自定义过滤器。你调试过代码吗?你能调试自定义过滤器代码吗?
  • 我更新我的问题并添加代码
  • 你使用的是什么版本的 MVC?

标签: c# asp.net-mvc


【解决方案1】:

对于 WebApi,您可以使用 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;
 }

【讨论】:

    【解决方案2】:

    如果您使用MVC 5.2.3,您的操作过滤器应如下所示。

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

    为了重定向到一个动作,你可以使用如下代码。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-08-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多