ASP.NET MVC:可用路由数据的Uri [英] ASP.NET MVC: Uri to usable route data
问题描述
我的问题很简单。我有一个Uri,我想弄清楚它所映射的路线,以便可以对路线的各个部分进行一些检查:控制器,动作等。
My problem is pretty simple. I've got a Uri and I want to figure out which route it maps to so I can do some checks on the various pieces of the route: controller, action, etc.
如何从Uri转到RouteData或Route?
How do I go from Uri to RouteData or Route?
推荐答案
基于@tvanfosson的指导,我想到了一个类那就是我需要的。请注意, GetRouteData
实际上会查看 AppRelativeCurrentExecutionFilePath
和 PathInfo
RequestContextBase
类中的属性,而不是 Url
属性中的属性。
Based on @tvanfosson's direction, I came up with a class that does what I need. Note that the GetRouteData
actually looks at the AppRelativeCurrentExecutionFilePath
and the PathInfo
properties on the RequestContextBase
class, not the Url
property.
public class RouteInfo
{
public RouteInfo(RouteData data)
{
RouteData = data;
}
public RouteInfo(Uri uri, string applicationPath)
{
RouteData = RouteTable.Routes.GetRouteData(new InternalHttpContext(uri, applicationPath));
}
public RouteData RouteData { get; private set; }
//********************
//Miscellaneous properties here to deal with routing conditionals... (e.g. "CanRedirectFromSignIn")
//********************
private class InternalHttpContext : HttpContextBase
{
private HttpRequestBase _request;
public InternalHttpContext(Uri uri, string applicationPath) : base()
{
_request = new InternalRequestContext(uri, applicationPath);
}
public override HttpRequestBase Request { get { return _request; } }
}
private class InternalRequestContext : HttpRequestBase
{
private string _appRelativePath;
private string _pathInfo;
public InternalRequestContext(Uri uri, string applicationPath) : base()
{
_pathInfo = uri.Query;
if (String.IsNullOrEmpty(applicationPath) || !uri.AbsolutePath.StartsWith(applicationPath, StringComparison.OrdinalIgnoreCase))
{
_appRelativePath = uri.AbsolutePath.Substring(applicationPath.Length);
}
else
{
_appRelativePath = uri.AbsolutePath;
}
}
public override string AppRelativeCurrentExecutionFilePath { get { return String.Concat("~", _appRelativePath); } }
public override string PathInfo { get { return _pathInfo; } }
}
}
这篇关于ASP.NET MVC:可用路由数据的Uri的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!