Question

I need to serialize some object into xml, which has string property "Url" - url of page returned by some action method (in asp.net mvc 3 app I want to implement custom rss).

I guess to call action method I just need to instantiate the controller which this method belongs to :)

MyController c = new MyContrroller();
c.MyActionMethod();

But how can I get the url of the page returned by this action method??

Edit 1: As the @SLaks answered we can use Url.Action() to get action method url, but how can I pass this url to the xml file?? If I just assign the result of Url.Action() to the link it will display the string: MyController/MyAction.

Was it helpful?

Solution

Pages returned by action methods do not have URLs.

Instead, the action methods themselves have URLs that come from the routing engine.

You can get the URL to an action by calling Url.Action(actionName, controllerName).

OTHER TIPS

I think there is no built in way to do what You need. You have to do it manually. For example like below:

public static class UrlExtension
{
    public static string ToAbsoluteUrl(this string relativeUrl, HttpContext httpContext)
    {
        string http = "http" + (httpContext.Request.IsSecureConnection ? "s" : string.Empty);
        string host = httpContext.Request.Url.Host;
        string port = httpContext.Request.Url.Port == 80 ? string.Empty : string.Format(":{0}", httpContext.Request.Url.Port);            

        return string.Format("{0}://{1}{2}{3}", http, host, port, relativeUrl);
    }
}

Example:

<a href="@Url.Action("Index", "Home").ToAbsoluteUrl(HttpContext.Current)">Index</a>
<a href="@Url.Action("TestAction", "Home").ToAbsoluteUrl(HttpContext.Current)">TestAction</a>

Render result:

<a href="http://localhost/">Index</a>
<a href="http://localhost/Home/TestAction">TestAction</a>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top