简体   繁体   中英

Asp.Net MVC view how to add script src from backend?

I have a MVC view where I am using Yandex external API for address search.

This is the script I have to add in order to use the Yandex services.

<script src="https://api-maps.yandex.ru/2.1/?apikey=xxxxxxxxxx&lang=ru_RU" type="text/javascript">

Is there a way to read this script src from the backend instead of directly using it in the View, as it contains the api key?

You can create an Action that loads and returns the script, then reference that Action in your html, eg:

<script src='@Url.Action("LoadYandex")'>

and

public ActionResult LoadYandex() {
    // HttpClient to get the file
    return Content(file, "text/javascript");
}

You can use a server side method to 'read' the script src file from the ASP.Net server. You would perform an HTTP GET using something like System.Net.Http.HttpClient . This is effective if you are retrieving JSON data or some other type of data to process on the server.

However, the C# backend would not process JavaScript instructions. For that you would need a server side JavaScript engine such as Node, or the client's web browser.

Including the JavaScript file in the View will allow the client's JavaScript engine to handle processing. But as you have implied, nothing in the View is hidden from the client.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM