seregazolotaryow64
@seregazolotaryow64
IT Специалист и самоучка

Как выполнить запрос к Mapbox JS API в ASP.NET Core Razor Pages?

Добрый день!

Так как я считаюсь новичком в ASP.NET Core и не только, недавно я столкнулся с тем, когда консоль браузера выдал сетевую ошибку соединения с Mapbox JS API на главной странице веб-приложения ASP.NET, жалуясь на отсутствие CORS

Сам шаблон приложения:
<!DOCTYPE html>
    <html lang="ru">
    <head>
        <meta charset="utf-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>@ViewData["Title"]</title>
        <link rel="stylesheet" href="~/lib/bootstrap/dist/css/bootstrap.min.css" />
        <link rel="stylesheet" href="~/css/site.css" />
        <script src='https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.js'></script>
    	<link href='https://api.mapbox.com/mapbox-gl-js/v2.3.1/mapbox-gl.css' rel='stylesheet' />
    
    </head>
    <body>
        <header>
            <nav class="navbar navbar-expand-sm navbar-toggleable-sm navbar-light bg-danger mb-3">
                <div class="container">
                    <a class="navbar-brand text-white fs-2" asp-area="" asp-page="/Index">My page</a>
                    <button class="navbar-toggler text-white" type="button" data-toggle="collapse" data-target=".navbar-collapse" aria-controls="navbarSupportedContent"
                            aria-expanded="false" aria-label="Toggle navigation">
                        <span class="navbar-toggler-icon"></span>
                    </button>
                    <div class="navbar-collapse collapse d-sm-inline-flex justify-content-between">
                        <ul class="navbar-nav flex-grow-1">
                            <li class="nav-item">
                                <a class="nav-link text-white fs-4" asp-area="" asp-page="/Index">First</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-white fs-4" asp-area="" asp-page="#">Two</a>
                            </li>
                            <li class="nav-item">
                                <a class="nav-link text-white fs-4" asp-area="" asp-page="/Privacy">Three</a>
                            </li>
                        </ul>
                    </div>
                </div>
            </nav>
        </header>
        <div class="container">
            <main role="main" class="pb-3" data-page="">
                @RenderBody()
            </main>
        </div>
    
        <footer class="border-top footer text-muted fs-5">
            <div class="container">
                &copy; 2021
            </div>
        </footer>
    
        <script src="~/lib/jquery/dist/jquery.min.js"></script>
        <script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
        <script src="~/js/site.js" asp-append-version="true"></script>
    
        @await RenderSectionAsync("Scripts", required: false)
    </body>
    </html>
Контроллер:
using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Mvc;
    using Microsoft.AspNetCore.Mvc.RazorPages;
    using Microsoft.Extensions.Logging;
    using Microsoft.AspNetCore.Cors;
    
    namespace frontend.Pages
    {
    	[EnableCors("MyPolicy")]
        public class IndexModel : PageModel
        {
            private readonly ILogger<IndexModel> _logger;
            public IndexModel(ILogger<IndexModel> logger)
            {
                _logger = logger;
            }
        }
    }

Само действие контроллера:

@page
    @model IndexModel
    @{
        ViewData["Title"] = "Home Page";
    }
    
    <div class="container">
    	<div class="col" id="map"></div>
    	<script>
    		mapboxgl.accessToken = 'pk.eyJ1Ijoic2VyZWdhem9sb3RhcnlvdzY0IiwiYSI6ImNrdGNuam91cTBlOWMyb3RkMGdleWt0ZW8ifQ.Z9JHSStCgSwJhaaRoLjD9w';
    		var map = new mapboxgl.Map({
    			container: 'map',
    			style: 'mapbox://styles/mapbox/streets-v11'
    		});
    	</script>
    </div>

И сам Startup.cs:

using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.HttpsPolicy;
    using Microsoft.AspNetCore.Cors;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    
    namespace frontend
    {
        public class Startup
        {
            public Startup(IConfiguration configuration)
            {
                Configuration = configuration;
            }
    
            public IConfiguration Configuration { get; }
    
    
            // This method gets called by the runtime. Use this method to add services to the container.
            public void ConfigureServices(IServiceCollection services)
            {
                services.AddRazorPages();
    
                services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
    			{
    				builder.AllowAnyOrigin()
    						.AllowAnyMethod()
    						.AllowAnyHeader();
    			}));
    
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
    			app.UseCors(builder => builder.AllowAnyOrigin());
    
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Error");
                    // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                    app.UseHsts();
                }
    
                app.UseHttpsRedirection();
    			app.UseStaticFiles();
    			app.UseRouting();
    			app.UseCors("MyPolicy");
    
    			// app.UseResponseCaching();
    
    			app.UseAuthorization();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapRazorPages();
    
                });
            }
        }
    }


Пролистывал документации и инструкции и ничего хорошего недало и само основание данного вопроса, с которым я обращаюсь к вам:

events.mapbox.com/events/v2?access_token=pk.eyJ1Ijoic2VyZWdhem9sb3RhcnlvdzY0IiwiYSI6ImNrdGNuam91cTBlOWMyb3RkMGdleWt0ZW8ifQ.Z9JHSStCgSwJhaaRoLjD9w:1 Failed to load resource: net::ERR_BLOCKED_BY_CLIENT
events.mapbox.com/events/v2?access_token=pk.eyJ1Ijoic2VyZWdhem9sb3RhcnlvdzY0IiwiYSI6ImNrdGNuam91cTBlOWMyb3RkMGdleWt0ZW8ifQ.Z9JHSStCgSwJhaaRoLjD9w:1 Failed to load resource: net::ERR_BLOCKED_BY_CLIENT


Как избавиться от этого? Заранее вам спасибо!
  • Вопрос задан
  • 73 просмотра
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Похожие вопросы