htmlasp.net-coreurlappsettings

.NET Core configuration URL ampersand encoding


I have a URL that I'd like to keep in appsettings.json :

"MapLookupURL": "https://www.google.com/maps/search/?api=1&query=",

I then retrieve this string via:

window.open("@(Configuration.MapLookupURL)" + 

The problem is .NET is encoding the string (including the ampersand in "&query=") thus rendering everything from the ampersand on useless.

How do I stop .NET from doing this?


Solution

  • Please try window.open("@(Html.Raw(_config["MapLookupURL"]))" + "Seoul");.

    Here's my test reult with codes below:

    @using Microsoft.Extensions.Configuration
    @inject IConfiguration _config
    @{
        ViewData["Title"] = "Home Page";
    }
    
    <div class="text-center">
        <h1 class="display-4">Welcome</h1>
        <p>Learn about <a href="https://docs.microsoft.com/aspnet/core">building Web apps with ASP.NET Core</a>.</p>
    </div>
    
    <button id="btn1">click to search</button>
    <div id="cont1">@_config["MapLookupURL"]</div>
    
    @section Scripts{
        <script>
            $("#btn1").click(function () {
                var a = @_config["MapLookupURL"];
                var b = "@Html.Raw(_config["MapLookupURL"])";
                console.info(a);
                window.open("https://www.google.com/maps/search/?api=1&query=" + "Seoul");
                // window.open("@_config["MapLookupURL"]" + "Seoul");
            })
        </script>
    }
    

    You will see that when the page loads, it already converts the asp.net core vaiable in js into plain html content. In the meantime, Razor automatically HTML-encodes any string output to prevent cross-site scripting (XSS) attacks. That's why we could see <div id="cont1">@_config["MapLookupURL"]</div> showed well(browser could show the encodes directly) but in <script> it doesn't. The workaround is using @Html.Raw(_config["MapLookupURL"]) which outputs the raw, unencoded string.

    enter image description here