Question

I am working on MVC application.

For test I was generating url as follows

private string CreateUserConfirmationLink(string confirmationToken)
{
    return string.Format("http://localhost:14834/Account/RegisterConfirmation?Id={0}", confirmationToken);
}

Now that I've published my application locally for testing, I realized that path is

http://localhost/Appname/...

So, the url that I'm generating doesn't work anymore. How do I generate the url that'll work for all the cases?

Is there some way to generate relative path and make it work?

PS: This method is in one of my repositories, not in controller.

Was it helpful?

Solution

Generate the "server" address of your action and then append the query string:

return string.Format(Url.Action("RegisterConfirmation", "Account")+"?Id={0}", confirmationToken);

or:

return string.Format(Url.Action("RegisterConfirmation", "Account", new {Id = confirmationToken });

and if you need a full absolute url, you can use this third version:

return string.Format(Url.Action("RegisterConfirmation", "Account", new {Id = confirmationToken }, Request.Url.Scheme);

If you need to generate the full url outside one of your controllers, use HttpContext.Current.Request.Url.Scheme instead of Request.Url.Scheme. In order to take advantage from Url.Action, if you call your CreateUserConfirmationLink method from one of your controllers (which I assume you do), you could modify the method to take the UrlHelper as input parameter:

private string CreateUserConfirmationLink(string confirmationToken, UrlHelper urlHelper)
{
    return string.Format(urlHelper.Action("RegisterConfirmation", "Account", new {Id = confirmationToken }, HttpContext.Current.Request.Url.Scheme);
}

Edit: for .Net 4 and above, the UrlHelper can be instantiated from the current context:

private string CreateUserConfirmationLink(string confirmationToken)
{
    UrlHelper urlHelper = new UrlHelper(HttpContext.Current.Request.RequestContext);

    return string.Format(urlHelper.Action("RegisterConfirmation", "Account", new {Id = confirmationToken }, HttpContext.Current.Request.Url.Scheme);
}

OTHER TIPS

try this

private string CreateUserConfirmationLink(string confirmationToken)
    {
       return string.Format(Url.Action("RegisterConfirmation", "Account", new {Id = confirmationToken});

    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top