Search code examples
c#asp.netasp.net-corevirtual-directoryvirtual-path

asp.net-core - Set response's virtual path with middleware


Setup

  • ASP.NET-Core web application hosted at https://first-domain.com/
  • Using a load-balancer to place the site under https://second-domain.com/some/path such that a request to https://second-domain.com/some/path/Page1 passes the request to https://first-domain.com/Page1
  • Sending headers when requests are forwarded:
    • X-Original-Host = 'second-domain.com'
    • X-Original-BasePath = 'some/path'
    • X-Original-Url = 'https://second-domain.com/some/path/Page1'
  • Pages use the ASP.NET root path character (~) to refer to resources relative to the application root.
  • Using ASP.NET-Core middleware to dynamically route the requests based on the headers.

Problem

My middleware correctly routes the request to the page. Based on the headers, requests to https://second-domain.com/some/path/PageX correctly retrieve the resource at https://first-domain.com/PageX.

However, PageX's URLs which use the ASP.NET root path character (~) are resolving to / so then the client tries to access resources at https://second-domain.com/ which don't exist.

For example, if PageX.cshtml had a <img src="~/myImage.png> tag, the client's browser will try to retrieve resource https://second-domain.com/myImage.png instead of https://second-domain.com/some/path/myImage.png

Question

Is there a way to manipulate the request and/or response with ASP.NET-Core middleware such that the ASP.NET root path (~) is resolved dynamically?

In other words, I'm trying to set a virtual path dynamically without using infrastructure-defined virtual paths via IIS/Azure.


Solution

  • This can be accomplished by setting context.Request.PathBase from the middleware.