Return absolute path from RouteBase.GetVirtualPath

public class CustomRoute : RouteBase { public override VirtualPathData GetVirtualPath(RequestContext requestContext, RouteValueDictionary routeValues) { var virtual_path_data = new VirtualPathData( this, "http://example.com" ); return virtual_path_data; } } 

ASP.NET seems to add a leading slash to any (absolute) path returned from VirtualPathData, returning /http://example.com in this example.

Question:

  • Is it possible to generate absolute URLs through RouteBase?
  • If not: then that would be the least ugly hack, so it works with Url.Action , RedirectToAction and other use cases that I don't know about.

Background

I wrote an XML-based routing mechanism that supports mutliple domain names. Therefore, when I create a URL that is available only in another domain, I would like to create an absolute URL, including the domain name.

 <host name="exm.com" controller="ShortUrl"> <parameter name="code" action="Redirect" /> </host> <host name="*" default="example.com" controller="Home" action="Index"> <x name="demo" controller="Home" action="Demo" /> <x name="comments" controller="Comment" action="List"> <x name="write" action="Write" /> <x name="delete" action="Delete" /> <x> </host> 

The result in combinations is like:

Url.Action("Demo", "Home")

http://example.com/demo

Url.Action("Write", "Comment")

http://example.com/comments/write

Url.Action("Redirect", "ShortUrl", new { code = "gH8x" } )

http://exm.cm/gH8x

Note that both example.com and exm.com refer to the same IP address of the application and are routed in the application.

+5
source share
2 answers

In the end, I made a relative ugly hack, where I prefix a special character to determine if it should be an absolute URL.

 public static string HostAction(this UrlHelper url, string actionName, string controllerName, object routeValues = null, bool forceOrigin = false) { var route_value_dictionary = CloneRouteValues( routeValues ); // this is being used in the routing to determine // if they need to route for an absolute URL route_value_dictionary.Add( "routeWithHostName", true ); // if forceOrigin is false, then the Routing will not return // an absolute path if it not necessary (url relative to the current domain) route_value_dictionary.Add("forceOrigin", forceOrigin ); var path = url.Action( actionName, controllerName, route_value_dictionary ); if ( path.Length < 2 ) return path; // starts with /$ ? then this is an absolute URL. Strip the first two characters if ( path[1] == '$' ) return path.Substring( 2 ); else return path; } 

Absolutely not perfect, but so far I seem to be running away with him, not breaking too much all the time.

0
source

Here's a blog post about someone who seems to have instructions for what you're trying to do. MVC Domain Routing

0
source

Source: https://habr.com/ru/post/1203133/


All Articles