Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
566 views
in Technique[技术] by (71.8m points)

asp.net mvc - Generating Route Url to MVC controller action from WebAPI

I'm used to generating route URLs to other controller actions within an MVC controller action using something similar to below:

public class ApplicationController : Controller
{
    public ActionResult Index( )
    {
        var url = Url.RouteUrl("routename",
           new { controller = "Application", Action = "Index2" , other="other" });
    }

    public ActionResult Index2( string other)
    {
    }
}

But I also need to be able to generate URLs to MVC controller actions from within webapi too, How would I go about doing this?

There seems to be a UrlHelper property on the APIController but I cant find any examples of how to use this and have not been able to figure it out myself.

UPDATE : The reason I am trying to generate a url is that this particular webapi method sends an email which provides the recipient with a link to direct the user back to an appropriate section of the site. I obviously want to get away from hardcoding this as it will not work for different deployments and also if I begin changing the routing this link will be broken. Is there a better approach to doing this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use MVC route names as well with web API UrlHelper. Example,

 Url.Link("Default", new { Controller = "Account", Action = "Login" });

or

 Url.Route("Default", new { Controller = "Account", Action = "Login" });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...