Сигнализатор не разрешает перекрестные запросы - PullRequest
0 голосов
/ 09 октября 2018

Это ошибка, которую я получаю.

Не удалось загрузить http://example.net/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D&_=1539104978557: Нет заголовка «Access-Control-Allow-Origin» на запрошенном ресурсе.Источник 'http://fictitiousite.com', следовательно, не имеет доступа.

Это запрос.

    Request URL: http://example.net/signalr/negotiate?clientProtocol=1.5&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D&_=1539104978557
Request Method: GET
Status Code: 200 OK
Remote Address: 52.187.135.79:80
Referrer Policy: no-referrer-when-downgrade

Это ответ:

Cache-Control: no-cache
Content-Type: application/json; charset=UTF-8
Expires: -1
Pragma: no-cache

Вот так выглядит мой класс запуска.

    public class Startup
{
    public void Configuration(IAppBuilder app)
    {
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationMode = AuthenticationMode.Active,
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Index")
        });


        var hubConfiguration = new HubConfiguration();
        hubConfiguration.EnableDetailedErrors = true;
        hubConfiguration.EnableJavaScriptProxies = true;
        hubConfiguration.EnableJSONP = true;

        app.MapSignalR("/signalr", hubConfiguration);



    }
}

У меня есть сайт 'http://fictitiousite.com', отправляющий http://example.net' запрос.

У меня нет проблемПринимая запросы от 'http://fictitiousite.com',, единственные запросы, которые не работают, это те, которые связаны с сигнализатором.

Это определения внутри моего web.config.

    <httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Headers" value="Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With" />
     <add name="Access-Control-Allow-Origin" value="http://fictitiousite.com" />     
    <add name="Access-Control-Allow-Methods" value="*" />
    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>
</httpProtocol>

Это функция запуска в моем global.asax.

protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{

            string[] allowedIps = new string[] {
                "52.117.111.111",
                "::1"
            };
            Uri MyUrl = Request.Url;
  string host = HttpContext.Current.Request.UserHostAddress;
              string cTheFile = HttpContext.Current.Request.Path;
            if (!cTheFile.EndsWith("Index") )
            {


                if (!allowedIps.Contains(host) )
                {

                    if (HttpContext.Current.User == null ||
                      HttpContext.Current.User.Identity == null ||
                      !HttpContext.Current.User.Identity.IsAuthenticated
                       )
                    {
                        Response.Redirect("~/Index", true);
                        Response.End();
                        return;
                    }

                }


            }
        }

Какое решение?почему соединение с сигнализатором отклоняется?

ОБНОВЛЕНИЕ

Следующие решения asp.net mvc не работают.

Решение 1:

public void Configuration(IAppBuilder app)
{
    app.Map("/signalr", map =>
    {
        map.UseCors(CorsOptions.AllowAll);
        var hubConfiguration = new HubConfiguration
        {
        };
        map.RunSignalR(hubConfiguration);
    });
}

Функция 'UseCors' не существует, т.е. существует ошибка компиляции.

Решение 2:

  RouteTable.Routes.MapHubs(new HubConfiguration()
        {
            EnableCrossDomain = true
        });

Visual Studio 2017 показывает, что этот кодустарела.

Какое еще решение?

Обновление 2:

Я обнаружил, что у меня пропал один пакет.

using Microsoft.Owin.Cors;

Этомое новое решение.

     app.Map("/signalr", map =>
        {
            // Setup the CORS middleware to run before SignalR.
            // By default this will allow all origins. You can 
            // configure the set of origins and/or http verbs by
            // providing a cors options with a different policy.
            map.UseCors(CorsOptions.AllowAll);
            var hubConfiguration = new HubConfiguration();
            hubConfiguration.EnableDetailedErrors = true;
            hubConfiguration.EnableJavaScriptProxies = true;
            hubConfiguration.EnableJSONP = true;
            // Run the SignalR pipeline. We're not using MapSignalR
            // since this branch already runs under the "/signalr"
            // path.
            map.RunSignalR(hubConfiguration);
        });

Я скоро протестирую его и сообщу.

После запуска соединения я получаю это странное сообщение.

jquery.signalR-2.3.0.min.js:9 WebSocket connection `

> to
> 'ws://localhost:64270/signalr/connect?transport=webSockets&clientProtocol=1.5&connectionToken=pHPJmk40WiuD882m3J0bt4cUn9bdIj96CrPg8fntHfjWm8DdrSnaB5UV7HG3LLQfOzRw9ZRBfzd1BMno39bsGaXyuBdkWNK2W%2FPQNKeUuI2ZP0DDRWs50ba5bQx20vXC&connectionData=%5B%7B%22name%22%3A%22chathub%22%7D%5D&tid=2'
> failed: Error during WebSocket handshake: Unexpected response code:
> 403

Соединениеустанавливает успешно (это позволяет мне отправлять сообщения), но я получаю эту ошибку.

Вот мои конфигурации.

            app.Map("/signalr", map =>
        {
            // Setup the CORS middleware to run before SignalR.
            // By default this will allow all origins. You can 
            // configure the set of origins and/or http verbs by
            // providing a cors options with a different policy.
            map.UseCors(CorsOptions.AllowAll);
            var hubConfiguration = new HubConfiguration();
            hubConfiguration.EnableDetailedErrors = true;
            hubConfiguration.EnableJavaScriptProxies = true;
          //  hubConfiguration.EnableJSONP = true;
            // Run the SignalR pipeline. We're not using MapSignalR
            // since this branch already runs under the "/signalr"
            // path.
            map.RunSignalR(hubConfiguration);
        });

Вот как я начинаю соединение.

$.connection.hub.start({ withCredentials: false }).done(function () { });

Нет ошибок до достижения этой линии.

...