信号器CORS问题

时间:2014-11-23 00:55:21

标签: asp.net angularjs signalr cors

在我的服务器端,我使用带有信号器的web api 2。 在我的客户端,我使用angularjs。

当我启动信号器连接时,这里是http请求:

> GET
> http://example.com/signalr/negotiate?clientProtocol=1.4&connectionData=%5B%7B%22name%22%3A%22main%22%7D%5D&_=1416702959615 HTTP/1.1 Host: mysite.net Connection: keep-alive Pragma: no-cache
> Cache-Control: no-cache Accept: text/plain, */*; q=0.01 Origin:
> http://lh:51408 User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64)
> AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.65
> Safari/537.36 Content-Type: application/x-www-form-urlencoded;
> charset=UTF-8 Referer: http://localhost:51408/ Accept-Encoding: gzip,
> deflate, sdch Accept-Language: en-US,en;q=0.8 Cookie:
> ARRAffinity=9def17406de898acdc2839d0ec294473084bbc94a8f600c867975ede6f136080

回复:

> HTTP/1.1 200 OK Cache-Control: no-cache Pragma: no-cache
> Transfer-Encoding: chunked Content-Type: application/json;
> charset=UTF-8 Expires: -1 Server: Microsoft-IIS/8.0
> X-Content-Type-Options: nosniff X-AspNet-Version: 4.0.30319
> X-Powered-By: ASP.NET Date: Sun, 23 Nov 2014 00:36:13 GMT
> 
> 187
> {"Url":"/signalr","ConnectionToken":"6BKcLqjNPyOw4ptdPKg8jRi7xVlPMEgFUdzeJZso2bnXliwfY4WReQWHRpmB5YEZsbg14Au7AS5k5xS5/4qVheDxYoUkOjfFW0W8eAQsasjBaSQOifIilniU/L7XQ1+Y","ConnectionId":"f2fc7c47-c84f-49b8-a080-f91346dfbda7","KeepAliveTimeout":20.0,"DisconnectTimeout":30.0,"ConnectionTimeout":110.0,"TryWebSockets":true,"ProtocolVersion":"1.4","TransportConnectTimeout":5.0,"LongPollDelay":0.0}
> 0

但是,在我的javascript中,我在连接时收到以下错误响应:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhos:51408' is therefore not allowed access.

在我的服务器端,我的启动方法如下所示:

public void Configuration(IAppBuilder app)
{
    System.Web.Mvc.AreaRegistration.RegisterAllAreas();
    ConfigureOAuth(app);
    GlobalConfiguration.Configure(WebApiConfig.Register);
    app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
}

这不是为了确保在信号器中也使用了cors,或者我错过了什么?

4 个答案:

答案 0 :(得分:6)

对于那些与Angular,SignalR 2.0和Web API 2.2存在相同问题的人,

我能够通过 web.config 中的添加cors配置以及 webapiconfig中没有来解决此问题。 cs startup.cs

<system.webServer>下的web.config所做的更改如下所示

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="http://localhost" />
    <add name="Access-Control-Allow-Methods" value="*" />
    <add name="Access-Control-Allow-Credentials" value="true" />
  </customHeaders>
</httpProtocol>

答案 1 :(得分:3)

您可以从此处查看此代码段https://github.com/louislewis2/AngularJSAuthentication/blob/master/AngularJSAuthentication.API/Startup.cs 并看看它是否有助于你。

public void Configuration(IAppBuilder app)
    {
        HttpConfiguration config = new HttpConfiguration();

        ConfigureOAuth(app);

        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
            {
                // You can enable JSONP by uncommenting line below.
                // JSONP requests are insecure but some older browsers (and some
                // versions of IE) require JSONP to work cross domain
                //EnableJSONP = true
                EnableDetailedErrors = true
            };
            // Run the SignalR pipeline. We're not using MapSignalR
            // since this branch already runs under the "/signalr"
            // path.
            map.RunSignalR(hubConfiguration);
        });

        WebApiConfig.Register(config);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseWebApi(config);
        Database.SetInitializer(new MigrateDatabaseToLatestVersion<AuthContext, AngularJSAuthentication.API.Migrations.Configuration>());

    }

答案 2 :(得分:0)

我在MVC.net中遇到了CORS问题

问题是SignalR协商XHR请求已发出凭据=包含,因此请求始终发送用户cookie

服务器必须使用响应标头Access-Control-Allow-Credentials设置为true进行回复

第一种方法,这是由于其他人的帮助,请在web.config中对其进行配置

<httpProtocol>
   <customHeaders>
      <add name= "Access-Control-Allow-Origin" value="http://yourdomain:port"/>
      <add name="Access-Control-Allow-Credentials" value = "true"/>
   </customHeaders>
</httpProtocol>

我努力使之起作用的第二种方法是使用OWIN CORS通过代码

[assembly::OwinStartup(typeof(WebHub.HubStartup), "Configuration"]
namespace WebHub
{
public class HubStartUp
{
    public void Configuration(IAppBuilder app)
    {
        var corsPolicy = new CorsPolicy
        {
            AllowAnyMethod = true,
            AllowAnyHeader = true,
            SupportsCredentials = true,
        };

        corsPolicy.Origins.Add("http://yourdomain:port");

        var corsOptions = new CorsOptions
        {
            PolicyProvider = new CorsPolicyProvider
            {
                PolicyResolver = context =>
                {
                    context.Headers.Add("Access-Control-Allow-Credentials", new[] { "true" });
                    return Task.FromResult(corsPolicy);
                }
            }
        };

        app.Map("/signalR", map =>
        {
            map.UseCors(corsOptions);
            var config = new HubConfiguration();
            map.RunSignalR(config);
        });
    }
}}

答案 3 :(得分:0)

在配置服务方法中:

services.AddCors(options => options.AddPolicy("CorsPolicy", builder =>
                 {
                    builder.AllowAnyHeader()
                           .AllowAnyMethod()
                           .SetIsOriginAllowed((host) => true)
                           .AllowCredentials();
                 }));

在配置方法中:

app.UseCors("CorsPolicy");
app.UseSignalR(routes =>
               {
                  routes.MapHub<General>("/hubs/general");
               });