我习惯使用类似于下面的内容生成到MVC控制器操作中的其他控制器操作的路由URL:
public class ApplicationController : Controller
{
public ActionResult Index( )
{
var url = Url.RouteUrl("routename",
new { controller = "Application", Action = "Index2" , other="other" });
}
public ActionResult Index2( string other)
{
}
}
Run Code Online (Sandbox Code Playgroud)
但我也需要能够从webapi中生成到MVC控制器动作的URL,我将如何进行此操作?
APIController上似乎有一个UrlHelper属性,但我找不到任何如何使用它的例子,但我自己也无法弄明白.
更新:我尝试生成URL的原因是这个特定的webapi方法发送一封电子邮件,该邮件向收件人提供一个链接,指导用户返回网站的相应部分.我显然希望摆脱硬编码,因为它不适用于不同的部署,如果我开始更改路由,这个链接将被破坏.有没有更好的方法来做到这一点?
asp.net-mvc asp.net-mvc-routing urlhelper asp.net-mvc-4 asp.net-web-api
如何判断字符串是否与特定的命名路由匹配?
我有这样的路线:
routes.MapRoute(
"FindYourNewRental",
"find-your-new-rental/{market}/{community}.html",
new { controller = "FindYourNewRental", action = "Community" }
);
string url = "http://www.website.com/find-your-new-rental/northerncalifornia/sacramento.html"
Run Code Online (Sandbox Code Playgroud)
如何以编程方式判断'url'字符串是否与该路由匹配?像这样的东西:
// matches url with the named route "FindYourNewRental"
if (IsRouteMatch(url, "FindYourNewRental"))
{
// do something
}
public bool IsRouteMatch(string url, string routeName)
{
// How do I code this function
}
Run Code Online (Sandbox Code Playgroud) 在给定的情况下,如何获取将要调用的控制器操作(方法)和控制器类型System.Web.Routing.RouteData?
我的情况是这样的 - 我希望能够在动作OnActionExecuting方法中执行某些动作(或不动作).
但是,我经常想知道当前的行动,而不是被称为"根"行动; 通过这个我的意思是我可能有一个名为"登录"的视图,这是我的登录页面.该视图可以包括另一个局部视图"LeftNav".当OnActionExecuting为LeftNav调用时,我希望能够确定它确实被称为Login的"root"aciton.
我意识到,通过调用RouteTable.Routes.GetRouteData(actionExecutingContext.HttpContext),我可以获得"root"请求的路由,但是如何将其转换为方法和类型信息?
到目前为止,我唯一的解决方案是:
var routeData = RouteTable.Routes.GetRouteData(actionExecutingContext.HttpContext)
var routeController = (string)routeData.Values["controller"];
var routeAction = (string)routeData.Values["action"];
Run Code Online (Sandbox Code Playgroud)
这个问题是"routeController"是删除了"Controller"后缀的控制器名称,并且不是完全限定的; 即它是"登录",而不是"MyCode.Website.LoginController".
我宁愿得到一个实际的Type,MethodInfo如果可能的话,或者至少是一个完全合格的类型名称.
有什么想法或替代方法吗?
[ 编辑 - 这是ASP.Net MVC 1.0]