4
votes

nugetPackage on .net core2.2.0:

signalr 1.0.0 + ASP.Core2.2.0

I'm using angular to connect use signalr:

package.json: "@aspnet/signalr": "1.1.0",

my angular front code:

import { Component } from '@angular/core';
import * as signalR from "@aspnet/signalr";


@Component({
    selector: 'app-root',
    templateUrl: './app.component.html'
})
export class AppComponent {
    constructor() { }


    private _hubConnection: signalR.HubConnection;
    msgs: Message[] = [];


    ngOnInit(): void {
        this._hubConnection = new signalR.HubConnectionBuilder()
            .withUrl('http://localhost:44390/chatHub')
            .build();
        this._hubConnection
            .start()
            .then(() => console.log('Connection started!'))
            .catch(err => console.log('Error while establishing connection :('));

        this._hubConnection.on('BroadcastMessage', (type: string, payload: string) => {
            this.msgs.push({ Type: type, Payload: payload });
        });
    }
}

export class Message {

    public Type: string
    public Payload: string
}       .catch(err => console.log('Error while establishing connection :('));

        this._hubConnection.on('BroadcastMessage', (type: string, payload: string) => {
            this.msgs.push({ Type: type, Payload: payload });
        });
    }

}

export class Message {

    public Type: string
    public Payload: string
}

my hub class:

using Microsoft.AspNetCore.SignalR; 
using System.Threading.Tasks;

namespace SharAPI.Models
{
    public class ChatHub : Hub 
    {
        public async Task BroadcastMessage(string msg)
        {
            await this.Clients.All.SendAsync("BroadcastMessage", msg);
        }
    }
}

startup.cs (ConfigureServices):

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(o => o.AddPolicy("MyPolicy", builder =>
    {
        builder.AllowAnyOrigin()
               .AllowAnyMethod()
               .AllowAnyHeader();
    }));
    services.AddSignalR();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

    // other codes
}

startup.cs (Configure):

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    app.UseResponseCompression();

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        // 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.UseSignalR(routes =>
    {
        routes.MapHub<ChatHub>("/chatHub");

    });
    app.UseCors(options => options.AllowAnyOrigin().AllowAnyHeader().AllowAnyMethod());

    app.UseMvc();

    //other codes
}

controller:

using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using SharAPI.Models;
using System;

namespace SharAPI.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    [EnableCors("MyPolicy")]

    public class MessageController : ControllerBase
    {
        private ChatHub _hub;
        public MessageController(ChatHub hub)
        {
            _hub  = hub ;
        }
        [HttpPost]
        public string Post([FromBody]Message msg)
        {
            string retMessage = string.Empty;
            try
            {
               _hub. BroadcastMessage(msg.message);
                retMessage = "Success";
            }
            catch (Exception e)
            {
                retMessage = e.ToString();
            }
            return retMessage;
        }
    }
}

and i get the error of:

Access to XMLHttpRequest at 'https://localhost:44390/chatHub/negotiate' from origin 'http://localhost:44390' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute

here is the pic

2
It seems that you need to configure CORS like app.UseCors(options => options.WithOrigins("http://localhost:57122").AllowAnyHeader().AllowAnyMethod().AllowCredentials());Ryan
Thanks for the reply, but the problem still remains – @Xing ZouSalar Kazazi

2 Answers

6
votes

You should add your CORS like this:

services.AddCors(options =>
{
    options.AddPolicy("CorsPolicy", builder => builder.WithOrigins("http://localhost:4200")
        .AllowAnyHeader()
        .AllowAnyMethod()
        .AllowCredentials()
        .SetIsOriginAllowed((host) => true));
});

Note:

The order is important!

1
votes

You should apply your policy in Configure method:

public void Configure 
{
    app.UseResponseCompression();

        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            // 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.UseCors("MyPolicy");
}

UPDATE:

If you are using localhost as http://localhost:4200, then try to set it in your configuration:

public void ConfigureServices(IServiceCollection services)
{
    services.AddCors(options => options.AddPolicy("ApiCorsPolicy", build =>
    {                
        build.WithOrigins("http://localhost:4200")
             .AllowAnyMethod()
             .AllowAnyHeader();
        }));
        // ... other code is omitted for the brevity
     }
}

And Configure method:

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    app.UseCors("ApiCorsPolicy");
    app.UseHttpsRedirection();        
    app.UseMvc();
}