How to change url by action filter and still redirect to executing route

时间:2018-09-22 22:41:42

标签: c# asp.net-core-mvc

Aim: I have a url like http://localhost:55830/shop/116_news - among other things, the filter has the task to change url to http://localhost:55830/shop/news

I tried:

filterContext.RouteData.Values[ActionFilter.Value] = "/shop/" + StringHelper.RemoveDiacritics(value.Value.ToLower());
filterContext.ActionArguments[ActionFilter.Value] = "/shop/" + StringHelper.RemoveDiacritics(value.Value.ToLower());
filterContext.HttpContext.Request.Path = "/shop/" + StringHelper.RemoveDiacritics(value.Value.ToLower());

None of above change url during OnActionExecuting

Whole action filter class:

public class ValueUrlFilterAttribute : ActionFilterAttribute
{
        private readonly IValueTypeRepository repositoryValueType;

        public ValueUrlFilterAttribute(IValueTypeRepository repoValueType)
        {
            repositoryValueType = repoValueType;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            string v = filterContext.RouteData.Values[ActionFilter.Value] as string;

            List<string> vInfo = ActionFilter.GetList(v);
            int valueId = ActionFilter.GetValueId(vInfo);
            string valueName = ActionFilter.GetValueName(vInfo);

            ValueType value = repositoryValueType.GetValueByValueId(valueId);

            if (value.Value.ToLower() == valueName)
            {
                object param;

                filterContext.RouteData.Values[ActionFilter.Value] = "/shop/" + StringHelper.RemoveDiacritics(value.Value.ToLower());
                filterContext.ActionArguments[ActionFilter.Value] = "/shop/" + StringHelper.RemoveDiacritics(value.Value.ToLower());
                filterContext.HttpContext.Request.Path = "/shop/" + StringHelper.RemoveDiacritics(value.Value.ToLower());

                if (filterContext.ActionArguments.TryGetValue("value", out param))
                {
                    filterContext.ActionArguments["value"] = value;
                }

                base.OnActionExecuting(filterContext);
            }
        }
}

I don't want to redirect to another action, I want to go to the action that I originally called

PS Sending new argument filterContext.ActionArguments["value"] = value; works great!

Issue I don't know how to change http://localhost:55830/shop/116_news to http://localhost:55830/shop/news

Thanks!

1 个答案:

答案 0 :(得分:1)

只需使用RouteAttribute con您的操作方法:

[Route("shop/news")]
public IActionResult AnythingHere()
{
   return View();
}

如果您需要从多个网址中删除116,请考虑在Startup.cs中创建一个全局模板,更多信息请参见:

https://docs.microsoft.com/en-us/aspnet/core/fundamentals/routing?view=aspnetcore-2.1

如果您想在浏览器中更改URL,那么没有重定向就无法实现。