如何知道所要求的路线

时间:2012-03-15 12:05:24

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

我正在撰写自定义Route课程,然后使用return RedirectToRoute("MyRouteName")

我怎么知道路线类中特别要求我自己的路线?

public bool IsRouteRequested()
{}

true会返回RedirecToRoute("MyRoute")false会返回RedirectToAction("SomeAction", "SomeController")

是否还可以检测是否从区域内调用RedirectToAction

2 个答案:

答案 0 :(得分:0)

也许你服务,我不太喜欢,但这是我唯一能想到的:

public static class RedirectToRouteResultExtensions
{
    private static IDictionary<RedirectToRouteResult, bool> typeRoute;

    public static RedirectToRouteResult SetRouteRequested(this RedirectToRouteResult redirectToRouteResult, bool value)
    {
        if (typeRoute == null)
        {
            typeRoute = new Dictionary<RedirectToRouteResult, bool>();
        }

        typeRoute[redirectToRouteResult] = value;

        return redirectToRouteResult;
    }

    public static bool IsRouteRequested(this RedirectToRouteResult redirectToRouteResult)
    {
        if (typeRoute == null)
        {
            return false;
        }

        return typeRoute.ContainsKey(redirectToRouteResult)
                    ? typeRoute[redirectToRouteResult]
                    : false;
    }
}

示例:

return RedirectToRoute("MyRouteName").SetRouteRequested(true);

return RedirectToAction("SomeAction", "SomeController");

*编辑解决方案II *

return RedirectToRoute("MyRouteName")之前,您可以在回复标题中添加信息:

HttpContext.Response.Headers.Add("CustomRoute", "1");
return RedirectToRoute("MyRouteName");

...

public bool IsRouteRequested()
{
   if (HttpContext.Response.Headers["CustomRoute"] != null &&
       HttpContext.Response.Headers["CustomRoute"] == "1")
       return true;  

   return false;

}

答案 1 :(得分:0)

您可以像这样定义路线值

return RedirectToRoute("myRoute", new { myVal = "val" });

然后检查它是否可用于GetVirtualPath

中的ex
public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary values)
    {
         if(values["myVal"] != null)....