2015-09-25 80 views
2

我試圖建立一個過濾器,在應用時傳閱「utm_」查詢字符串PARAMSASP.MVC濾波器參數

這是我想出了:

public class PassAlongParametersFilter : FilterAttribute, IResultFilter 
{ 
    public string Filter { get; set; } 

    public PassAlongParametersFilter() 
    { 
     Filter = "*"; 
    } 

    public void OnResultExecuting(ResultExecutingContext filterContext) 
    { 
    } 

    public void OnResultExecuted(ResultExecutedContext filterContext) 
    { 
     if (filterContext.Result is RedirectToRouteResult) 
     { 
      var action = (RedirectToRouteResult) filterContext.Result; 

      var qs = filterContext.RequestContext.HttpContext.Request.QueryString; 

      var regex = StringUtils.WildcardToRegex(Filter); 

      var routeValues = action.RouteValues; 

      qs.AllKeys.Where(e => Regex.IsMatch(e, regex)).ForEach(s => routeValues[s] = qs[s]); 

      filterContext.Result = new RedirectToRouteResult(action.RouteName, routeValues, action.Permanent); 
     } 
    } 
} 

我可以在調試時看到正在填充的routeValues,但utm參數不包含在生成的url中。

這是過濾器的動作:

[HttpPost] 
[AllowAnonymous] 
[PassAlongParametersFilter(Filter = "utm_*")] 
[Route("konto/registrera/externt/{campaignCode}")] 
public ActionResult SimpleRegisterExternal(string email, string campaignCode) 
{ 

這是我嘗試重定向到行動:

[AllowAnonymous] 
[Route("konto/registrera/tack")] 
public ActionResult RegisterThanks(RegisterThanksViewModel model) 
{ 

我猜有什麼東西與路由?

回答

3

好,所以我想通了。在OnResultExecuted中替換結果爲時已晚。以下是我最終得到的結果:

public class PassAlongParametersFilter : ActionFilterAttribute 
    { 
     public string Filter { get; set; } 

     public PassAlongParametersFilter() 
     { 
      Filter = "*"; 
     } 

     public override void OnActionExecuted(ActionExecutedContext filterContext) 
     { 
      if (filterContext.Result is RedirectToRouteResult) 
      { 
       var action = (RedirectToRouteResult)filterContext.Result; 

       var qs = filterContext.RequestContext.HttpContext.Request.QueryString; 

       var regex = StringUtils.WildcardToRegex(Filter); 

       var routeValues = action.RouteValues; 

       qs.AllKeys.Where(e => Regex.IsMatch(e, regex)).ForEach(s => routeValues[s] = qs[s]); 

       filterContext.Result = new RedirectToRouteResult(action.RouteName, routeValues, action.Permanent); 
      } 
     } 

    }