如何使用querystring从ActionFilterAttribute请求重定向

时间:2018-08-27 10:30:43

标签: c# redirect model-view-controller actionfilterattribute

我必须将任何请求重定向到规范网址。为了解决此任务,我使用派生的ActionFilterAttribute,例如下面的代码:

public class CheckToRedirectFilterAttribute : ActionFilterAttribute
{
    public bool ExactUrl { get; set; } = true;
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        base.OnActionExecuting(filterContext);

        ActionResult redirect = filterContext.RouteData.RedirectToNewMap();
        if (redirect == null && this.ExactUrl) {
            var urlHelper = new UrlHelper(filterContext.RequestContext);
            var routeValues = filterContext.RouteData.Values;
            foreach (var a in filterContext.ActionParameters)
            {
                if (!routeValues.ContainsKey(a.Key))
                    routeValues.Add(a.Key, a.Value);
            }
            var canonicUrl = urlHelper.Action(filterContext.ActionDescriptor.ActionName, filterContext.ActionDescriptor.ControllerDescriptor.ControllerName, filterContext.RouteData.Values);
            if (filterContext.HttpContext.Request.RawUrl.ToLower() != canonicUrl)
                redirect = new RedirectResult(canonicUrl.ToLower());
        }
        if (redirect != null)
        {
            filterContext.Result = redirect;
        }
    }
}

然后在操作方法上使用此属性:

public class HomeController : Controller
{
    [CheckToRedirectFilter]
    public ActionResult Index()
    {
        return View();
    }
}

0 个答案:

没有答案