Tiago B
Tiago B

Reputation: 2065

How to create URL Link outside UI Project?

I have a MVC 3 application project, that references a ServiceProject which executes commands like CreateNewPost(Foo entity)...

IMPORTANT: This ServiceProject cant reference System.Web.MVC

I need to create an email(this method is on my ServiceProject), that contains a url link to some specific page (example TestController/FooAction) on my system, but I want to create a relative URL, that will generate correctly on production environment, test environment, or even develop environment(localhost).

How do I create that URL?

Upvotes: 0

Views: 1158

Answers (3)

talles
talles

Reputation: 15086

One obvious way is to pass a base url to the methods (or maybe to the entire project by dependency injection).


Another way, if you can reference System.Web and there is a HTTP request involved, you can use

HttpContext.Request.Url.Scheme + "://" +  HttpContext.Request.Url.Authority + HttpContext.Request.ApplicationPath

Scheme gives you the url scheme (a.k.a. protocol).

Authority gives you the hostname and port for the request server.

ApplicationPath gives you the virtual root path of the ASP.NET application on the server.


Looks like you can't do it without a HttpRequest, as previously answered here.

Upvotes: 2

Nick Butler
Nick Butler

Reputation: 24383

If you can't reference System.Web.MVC, you can't use UrlHelper.

However, you can use the System.Uri class which is in System.dll

So you could calculate the base uri in your web project, pass it as a string to your service project and then use Uri to create the final uri:

// controller in web project
ServiceProject.SendEmail( Url.Content( "~" ), ... );

// service project
public void SendEmail( string baseUriAsString, ... )
{
  var baseUri = new Uri( baseUriAsString, UriKind.Absolute );
  string relativeUri = ...
  var finalUri = new Uri( baseUri, relativeUri );
  ...

See MSDN: System.Uri

Upvotes: 0

Middas
Middas

Reputation: 1870

This does require reference to System.Web.MVC, but it should give you a basic idea how it can be done. I created an extension to help me with this:

    public static string GetAbsoluteURL(this RouteCollection routes, RequestContext context, RouteValueDictionary values, HttpProtocolType httpProtocol)
    {
        string host;

        if (context.HttpContext.Request.Url != null)
        {
            host = context.HttpContext.Request.Url.Authority;
        }
        else
        {
            host = context.HttpContext.Request.UrlReferrer.Host;
        }

        string virtualPath = routes.GetVirtualPath(context, "Default", values).VirtualPath;

        string protocol = httpProtocol == HttpProtocolType.HTTP ? "http" : "https";

        return string.Format("{0}://{1}{2}", protocol, host, virtualPath);
    }

Upvotes: 2

Related Questions