Your PC can't even

C# – Environment UrlExtensions

This post documents how to extend the baseline UrlExtensions in MVC in order to add Environment extensions.

Why? How is this useful?

When you have a collection of microservices, there is a chance that some of them may live on another web page or domain. For these types of CORs ajax-framed components, using a baseline MVC Url helper will not work. The baseline helpers will resolve your action or content based upon the path of the hosting solution. These paths will not exist on the framing site. As such, these extensions will build a fully-qualified Url back to your endpoint.

Implementing the class

public static class UrlExtensions {
        public static string EnvironmentAction(this UrlHelper helper, string ActionName, string ActionController) {
        string result = helper.Action(ActionName, ActionController);
        return string.Format("{0}{1}", System.Configuration.ConfigurationManager.AppSettings["EnvUrl"], result);
        public static string EnvironmentContent(this UrlHelper helper, string ContentPath, bool FromHeader = false) {
        //Call into base UrlContent to resolve the partial
        string result = helper.Content(ContentPath);
        //Concat partial with envresult to obtain fully qualified path
        if (!FromHeader) return string.Format("{0}{1}", System.Configuration.ConfigurationManager.AppSettings["EnvUrl"], result);
        else return result;

Web.config markup; Local, Debug, Release.

        <!--For local IIS-->
        <add key="EnvUrl" value="http://localhost" />
Web.Debug.config and Web.Release.config
        <add key="EnvUrl" p3:Transform="Replace" p3:Locator="Match(key)" value="" xmlns:p3="" />
Usage, inside .cshtml file using the Razor engine.
Calling an action from ajax.
        type: "POST",
        dataType: "json",
        url: "@Url.EnvironmentAction("MyServerSideAction", "MyController")",
        data: someData,
        success: function (data, textStatus, jqXHR) {
        error: function () {
Populating a Url.
<link href=@Url.EnvironmentContent("~/Content/bootstrap.css") rel="stylesheet" />
<script src=@Url.EnvironmentContent("~/Scripts/jquery.min.js")></script>