Error failed to complete negotiation with the server error

This blog provides a solution to the signalR hub connection issue such as Error: Failed to complete negotiation with the server: Error: Not Found: Status code ‘404’ Either this is not a SignalR endpoint or there is a proxy blocking the connection.

I was working on ASP.NET Core SignalR client application to receive the message from the SignalR hub. This is the scenario where my SignalR server and client were two separate .NET Core applications. In the client application, I got the below error message while trying to receive the message from SignalR Hub(server). This error may arise and the solution is almost similar for both cases using SignalR Javascript client and .NET Client.

Exact Error Message: “Error: Failed to complete negotiation with the server: Error: Not Found: Status code ‘404’ Either this is not a SignalR endpoint or there is a proxy blocking the connection.”

Below is my earlier code:

var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:39823/event-hub)

Then to resolve the above error I found that we need to add the below code in HubConnectionBuilder.

skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets

Note that: The negotiation should be skipped only when the transport property is set to ‘signalR.HttpTransportType.WebSockets‘.

Solution

Below is the previous code with which I got an error.

var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:4023/yourevent)

Complete code to resolve the issue.

var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:4023/yourevent", {
    skipNegotiation: true,
    transport: signalR.HttpTransportType.WebSockets
})

Note: This solution is applicable for both cases either using the SignalR .NET client or SignalR JavaScript client.

I hope you have got an idea of how to resolve this error.


Post Views:
4,215

I was working on ASP.NET Core SignalR client application to receive the message from the SignalR hub. This is the scenario where my SignalR server and client were two separate .NET Core applications. In the client application, I got the below error message while trying to receive the message from SignalR Hub. This error may arise and the solution is almost similar for both cases using SignalR Javascript client and .NET Client.

Exact Error Message: “Error: Failed to complete negotiation with the server: Error: Not Found: Status code ‘404’ Either this is not a SignalR endpoint or there is a proxy blocking the connection.”

Earlier code:

var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:39823/event-hub)

Then to resolve the above error I found that we need to add the below code in HubConnectionBuilder.

skipNegotiation: true,
transport: signalR.HttpTransportType.WebSockets

Note that: The negotiation should be skipped only when the transport property is set to ‘signalR.HttpTransportType.WebSockets‘.

Solution

Below is the earlier code with the error.

var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:4023/yourevent)

Complete code to resolve the issue.

var connection = new signalR.HubConnectionBuilder().withUrl("http://localhost:4023/yourevent", {
    skipNegotiation: true,
    transport: signalR.HttpTransportType.WebSockets
})

Note: This solution is applicable for both cases either using SignalR .NET Client or SignalR JavaScript client.

image

Client Code:

import React, {Component} from ‘react’;
import * as signalR from ‘@aspnet/signalr’;

class Notification extends Component {

constructor(props) {
    super(props);
    
    this.state = {
      nick: '',
      message: '',
      messages: [],
      hubConnection: null,
    };
  }

  componentDidMount = () => {
    const nick = window.prompt('Your name:', 'John');

    let hubConnection = new signalR.HubConnectionBuilder()
    .withUrl("https:/######################.#######.#####.net",
    {accessTokenFactory: () => #####################################' })
    .configureLogging(signalR.LogLevel.Trace)
     .build();
     
    this.setState({ hubConnection, nick }, () => {  
      this.state.hubConnection
        .start()
        .then(() => console.log('Connection started!'))
        .catch(err => console.log('Error while establishing connection :('));

      this.state.hubConnection.on('sendToAll', (nick, receivedMessage) => {
        const text = `${nick}: ${receivedMessage}`;
        const messages = this.state.messages.concat([text]);
        this.setState({ messages });
      });
    });
  }
  sendMessage = () => {
    this.state.hubConnection
      .invoke('sendToAll', this.state.nick, this.state.message)
      .catch(err => console.error(err));
  
      this.setState({message: ''});      
  };

render() {
    return(
        <>
            <div>
                Hiiiii
            </div>
            <div>
                <br />
                <input
                    type="text"
                    value={this.state.message}
                    onChange={e => this.setState({ message: e.target.value })}
                />

                <button onClick={this.sendMessage}>Send</button>

                <div>
                    {this.state.messages.map((message, index) => (
                    <span style={{display: 'block'}} key={index}> {message} </span>
                    ))}
                </div>
            </div>
        </>
    );}

}
export default Notification;

I am trying to communicate with Azure SignalR using react js client. I am very new with azure and react js. Could you please help me how can I resolve this issue? Thanks in advance.

Содержание

  1. React Native app won’t complete negotiation with SignalR Core
  2. 2 Answers 2
  3. Linked
  4. Related
  5. Hot Network Questions
  6. Subscribe to RSS
  7. Rijwan & Satya’s Blog
  8. Resolve: SignalR Error: Failed to complete negotiation with the server
  9. By Satya Karki
  10. Angular/SignalR Error: Failed to complete negotiation with the server
  11. 8 Answers 8
  12. .NET Core SignalR, Тайм-аут сервера / проблема переподключения
  13. 3 ответа
  14. SignalR connection to Azure not working (.net core 3.1)
  15. 1 Answer 1

React Native app won’t complete negotiation with SignalR Core

I’m trying to integrate the SignalR Core JS client on React Native but can’t quite seem to get it to work with a ASP.NET Core server with SignalR. I’ve heard that other people have been able to make it work despite the lack of a designated React Native client.

I keep getting the following error: «Error: Failed to complete negotiation with the server: Error». Could someone help me?

Here’s what the React Native app looks like:

Here’s what the server looks like:

Demo1.cs project file

2 Answers 2

Turns out React Native had an issue connecting perhaps because of the https protocol. Furthermore, I also explicitly added ‘Microsoft.AspNetCore.SignalR’ version 1.0.4 to match the version on React Native even though it should be included in ‘Microsoft.AspNetCore.App’.

So, here’s the updated code that works on both React and React Native:

Here’s what the server looks like:

Demo1.cs project file

As I understand, this problem is already solved, however, I thought I might share a solution to the problem I encountered (resulting in the same error message = «Error: Failed to complete negotiation with the server: Error»).

The cause of my problem was that I specified a wrong port number in the client code. (as a parameter passed to HubConnectionBuilder().withUrl() method)

So instead of the «demo1″‘s applicationUrl (http://192.168.0.89:5000), I needed to pass the iisExpress’ applicationUrl (http://192.168.0.89:5002).

Linked

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.1.14.43159

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Rijwan & Satya’s Blog

Learn developer and data technologies with us

Resolve: SignalR Error: Failed to complete negotiation with the server

By Satya Karki

I was working on ASP.NET Core SignalR client application to receive the message from the SignalR hub. This is the scenario where my SignalR server and client were two separate .NET Core applications. In the client application, I got the below error message while trying to receive the message from SignalR Hub. This error may arise and the solution is almost similar for both cases using SignalR Javascript client and .NET Client.

Exact Error Message: “Error: Failed to complete negotiation with the server: Error: Not Found: Status code ‘404’ Either this is not a SignalR endpoint or there is a proxy blocking the connection.”

Earlier code:

Then to resolve the above error I found that we need to add the below code in HubConnectionBuilder.

Note that: The negotiation should be skipped only when the transport property is set to ‘signalR.HttpTransportType.WebSockets‘.

Solution

Below is the earlier code with the error.

Complete code to resolve the issue.

Note: This solution is applicable for both cases either using SignalR .NET Client or SignalR JavaScript client.

Источник

Angular/SignalR Error: Failed to complete negotiation with the server

Using SignalR for my server and Angular for my client. When I run my client I receive these errors:

I am guessing it is something with CORS. I am trying to implement a simple chat application. I am using the latest verison of SignalR:

Here is the github that contains the code for the tutorial I am following. SignalR Chat Tutorial

Here is my startup

And here is my client:

I assume it may be something with cors. Thank you!

EDIT: I just recreated the signalr implementation in visual studio and it worked. I believe I chose the wrong settings on start up.

8 Answers 8

I faced the slimier issue and I fixed it by adding

in client-side as @Caims mentioned. But I don’t think this is the correct solution and feel more like a hack 😊. What you have to do is adding AllowCredentials in server side. Anyway when it’s coming to Azure you can’t relay on that fix. So no need enable WSS only in client side.

Here is my ConfigureServices method:

This is my Configure method:

And finally this is how I connected from client-side:

I had the same problem, and it turns out that the launchSettings.json in the part where it says signalRchatServer does nothing, the url that worked with me was that of the iisexpress, I say it because there are many places where they say that the url is the one below .

I was pointing to the wrong endpoint. I was using

https://localhost:5001/api/message-hub instead of

https://localhost:5001/message-hub (extra /api)

Also if you’re using Angular, you’re likely to get a Websocket not OPEN error right after fixing this one, so here’s a link to save you from more searches.

I waste almost two days for this and finally figured out,

When this error occurs?

  • When you upgrade your existing SignalR server project to .Net Core but do not upgrade the client
  • When you create the SignalR server using .Net core but you use traditional .Net framework for the client

Why this error occurs?

The error occurs because new SignalR does not allow you to use old server & new client or new server & old client

It means if you create the SignalR server using .Net core then you must create the client using .Net Core

Источник

.NET Core SignalR, Тайм-аут сервера / проблема переподключения

У меня есть концентратор SignalR, написанный в моем решении MVC, с подключением клиента Javascript из представления.

Точка подключения заключается в получении изменений для настенного экрана от сервера. Это должно произойти почти мгновенно и требует пожизненного соединения, поскольку веб-страница работает на экране без прямого доступа к компьютеру.

Пока соединение SignalR работает в течение нескольких часов, прежде чем выдает ошибку.

Я получаю ошибку

Мой код клиента

Вопрос 1: Правильно ли я справляюсь с переподключением? Из-за ошибки кажется, что .onclose работает, но что он пытается только один раз? Есть ли в любом случае, чтобы попытаться на х мин, прежде чем показать ошибку?

Вопрос 2: перезагрузка веб-сайта заставляет соединение работать снова, есть ли возможность обновить браузер при ошибке соединения signalR?

3 ответа

У меня та же проблема (вопрос 1), и я решаю с этим:

Каждые 5 секунд пытается восстановить соединение, но я не знаю, является ли это правильным способом сделать это.

Для настройки автоматического переподключения требуется только вызов withAutomaticReconnect на HubConnectionBuilder. Вот как выглядит мой код JavaScript для настройки моего соединения:

Вы можете настроить период отсрочки, передав массив задержек повторных попыток вызову withAutomaticReconnect (). По умолчанию для этого используется [0, 2000, 10000, 30000, ноль]. Нулевое значение указывает SignalR прекратить попытки. Так, например, если я хочу повторить попытку через 0, 1 секунду и 5 секунд, я могу настроить свой HubConnectionBuilder следующим образом:

В ASP.NET Core 2.1 (текущий выпуск LTS) с соответствующим выпуском SignalR, похоже, не существует какого-либо интегрированного метода переподключения. Код из @Shidarg не работает для меня, он вызывает метод Reconnect в бесконечном цикле сбой моего браузера. Мне также больше нравится синтаксис async / await из C #, поэтому я обновил его:

Но для ASP.NET Core 3 они включили метод переподключения:

По умолчанию он пытается выполнить три повторных подключения: сначала через 2 секунды, затем через 10 секунд и последнее примерно через 30 секунд. Это можно изменить, передав интервалы в качестве параметра массива:

Источник

SignalR connection to Azure not working (.net core 3.1)

Am trying to connect my App with Azure SignalR, but does not seem to establish connection.

It all works fine when I use in my basic config file and run the program locally:

But when I change it to Azure like this (I hardcoded the key here)

I get errors on the client side saying

«Failed to load resource: the server responded with a status of 500 (Internal Server Error)»

«Error: Failed to complete negotiation with the server: Error: Internal Server Error»

I managed to get the full server Log file below. Any pointer would be greatly appreciated. I can still chose to run SignalR by default and not use the Azure one, but I have thousands of calls on SignalR and Azure seems to explain using their service would be faster.

1 Answer 1

This happened to me on the day of my sprint review, when we reached the max message count for our free tier Azure SignalR service. As you can see in your log, you rechead the 20k messages limit.

crit: Microsoft.Azure.SignalR.ServiceConnection[24] Service returned handshake error: Maximum message count limit reached: 20000. Id: 535de32b-cedb-4cda-9959-675e6712f6ac

info: Microsoft.AspNetCore.Http.Connections.Client.Internal.WebSocketsTransport[11] WebSocket closed by the server. Close status NormalClosure.

dbug: Microsoft.AspNetCore.Http.Connections.Client.HttpConnection[4] Disposing HttpConnection.

You can just create a new free tier Azure SignalR service and change the key for the new one or upgrade. During our development we just created new ones before it was almost completed and change it for the standard tier.

Источник

Add Answer
|
View In TPC Matrix

Technical Problem Cluster First Answered On
April 26, 2022

Popularity
5/10

Helpfulness
4/10


Contributions From The Grepper Developer Community

Contents

Code Examples

  • Error: Failed to complete negotiation with the server: Error signalr
  • Related Problems

  • failed to complete negotiation with the server: error
  • TPC Matrix View Full Screen

    Error: Failed to complete negotiation with the server: Error signalr

    Comment

    0


    Popularity

    5/10 Helpfulness
    4/10
    Language
    whatever

    Source: stackoverflow.com

    Tags: signalr
    whatever

    Monalisa Silva

    Contributed on Apr 26 2022

    Monalisa Silva

    3 Answers  Avg Quality 5/10


    Using SignalR for my server and Angular for my client... When I run my client I receive these errors:
    zone.js:2969 OPTIONS https://localhost:27967/chat/negotiate 0 ()
    Utils.js:148 Error: Failed to complete negotiation with the server: Error
    Utils.js:148 Error: Failed to start the connection: Error
    I am guessing it is something with CORS... I am trying to implement a simple chat application. I am using the latest verison of SignalR:
    Here is the github that contains the code for the tutorial I am following.
    SignalR Chat Tutorial
    Here is my startup
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.DependencyInjection;
    namespace signalrChat
    {
    public class Startup
    {
    // This method gets called by the runtime. Use this method to add services to the container.
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
    public void ConfigureServices(IServiceCollection services)
    {
    services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
    {
    builder
    .AllowAnyMethod()
    .AllowAnyHeader()
    .WithOrigins("http://localhost:4200");
    }));
    services.AddSignalR();
    }
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
    if (env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    }
    app.UseCors("CorsPolicy");
    app.UseSignalR(routes =>
    {
    routes.MapHub<ChatHub>("/chat");
    });
    }
    }
    }
    And here is my client:
    import { Component, OnInit } from '#angular/core';
    import { HubConnection, HubConnectionBuilder } from '#aspnet/signalr';
    #Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
    private hubConnection: HubConnection;
    nick = '';
    message = '';
    messages: string[] = [];
    ngOnInit() {
    this.nick = window.prompt('Your name:', 'John');
    this.hubConnection = new HubConnectionBuilder().withUrl('https://localhost:27967/chat').build();
    this.hubConnection
    .start()
    .then(() => console.log("Connection Started!"))
    .catch(err => console.log("Error while establishing a connection :( "));
    this.hubConnection.on('sendToAll', (nick: string, receiveMessage: string) => {
    const text = `${nick}: ${receiveMessage}`;
    this.messages.push(text);
    })
    }
    public sendMessage(): void {
    this.hubConnection
    .invoke('sendToAll', this.nick, this.message)
    .catch(err => console.log(err));
    }
    }
    I assume it may be something with cors. Thank you!
    EDIT: I just recreated the signalr implementation in visual studio and it worked. I believe I chose the wrong settings on start up.
    

    connection = new signalR.HubConnectionBuilder()
    .configureLogging(signalR.LogLevel.Debug)
    .withUrl("http://localhost:5000/decisionHub", {
    skipNegotiation: true,
    transport: signalR.HttpTransportType.WebSockets
    })
    .build();
    

    I was facing the same problem in my Angular application when I try to connect to Azure SignalR service Azure Function.
    [FunctionName("Negotiate")]
    public static IActionResult Run(
    [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, [SignalRConnectionInfo(HubName = "broadcast")] SignalRConnectionInfo info,
    ILogger log) {
    log.LogInformation("Negotiate trigger function processed a request.");
    return info != null ? (ActionResult) new OkObjectResult(info) : new NotFoundObjectResult("SignalR could not load");
    }
    And below was my init() function code in Angular service.
    init() {
    this.getSignalRConnection().subscribe((con: any) => {
    const options = {
    accessTokenFactory: () => con.accessKey
    };
    this.hubConnection = new SignalR.HubConnectionBuilder()
    .withUrl(con.url, options)
    .configureLogging(SignalR.LogLevel.Information)
    .build();
    this.hubConnection.start().catch(error => console.error(error));
    this.hubConnection.on('newData', data => {
    this.mxChipData.next(data);
    });
    });
    }
    My problem was with the con.accessKey. I just checked the properties of the SignalRConnectionInfo class and understood that I need to use accessToken instead of accessKey.
    public class SignalRConnectionInfo {
    public SignalRConnectionInfo();
    [JsonProperty("url")]
    public string Url {
    get;
    set;
    }
    [JsonProperty("accessToken")]
    public string AccessToken {
    get;
    set;
    }
    }
    So after changing the code to accessTokenFactory: () => con.accessToken everything worked as usual.

    Related

    SignalR workaround to get client data from server

    I know that SignalR can't have a return from client when invokation came from the server. On the github repository of SignalR I asked for a workaround (https://github.com/aspnet/SignalR/issues/1329) and they suggest me to get the result by sending it from the client to server to another method in the hub and so use TaskCompletionSource and some connection metadata to catch the result, but I'm stuck on how to do this
    Controller Server :
    [HttpPut("send/{message}")]
    public async Task<IActionResult> SendMessage(string message)
    {
    if (!ModelState.IsValid) return BadRequest(ModelState.Values);
    string connectionId = Request.Headers["connectionId"];
    await _chatHubContext.Clients.Client(connectionId).InvokeAsync("send");
    // Catch the call of MessageReceived and get the chat status
    return new OkObjectResult(new EmptyJsonResult() { Result = "OK" });
    }
    Hub Server
    public class ChatHub : Hub
    {
    public Task MessageReceive(bool chatStatus)
    {
    // Tell controller that message is received
    }
    }
    Angular 4 client
    import { Component, Inject } from '#angular/core';
    import { HubConnection } from '#aspnet/signalr-client';
    #Component({
    selector: 'chat',
    templateUrl: './chat.component.html',
    styleUrls: ['./chat.component.css']
    })
    /** chat component*/
    export class ChatComponent {
    hubConnection: HubConnection;
    chatStatus = false;
    /** chat ctor */
    constructor( #Inject('BASE_URL') private originUrl: string) {
    this.hubConnection = new HubConnection(`${this.originUrl}chat`);
    setInterval(() => {
    this.chatStatus = !this.chatStatus;
    },
    5000);
    this.hubConnection
    .start()
    .then(() => {
    this.hubConnection.on('send', (message: string) => {
    if (this.chatStatus) {
    //send message
    }
    this.hubConnection
    .invoke('messageReceived', this.chatStatus);
    });
    });
    }
    }
    As you can see on this code, I don't know what to do in the controller method and the Hub method to know that the method MessageReceive was called and to get his return to send it back to the controller request.
    
    "with a little hacking around with connection metadata and TaskCompletionSource you could also probably make it look a lot like a method invocation returning a value."
    Controller server:
    Inject HttpConnectionManager.
    // using Microsoft.AspNetCore.Http.Connections.Internal;
    public async Task<IActionResult> SendMessage(string message)
    {
    string connectionId = Request.Headers["connectionId"];
    var chatStatus = await Send(connectionId, message);
    return new OkObjectResult(new { Result = "OK", ChatStatus = chatStatus });
    }
    private async Task<bool> Send(string connectionId, string message)
    {
    var tcs = new TaskCompletionSource<bool>();
    _connectionManager.TryGetConnection(connectionId, out HttpConnectionContext connection);
    connection.Items.Add("tcs", tcs);
    await _chatHubContext.Clients.Client(connectionId).SendAsync("send", message);
    var chatStatus = await tcs.Task;
    connection.Items.Remove("tcs");
    return chatStatus;
    }
    Hub server:
    public Task MessageReceived(bool chatStatus)
    {
    Context.Items.TryGetValue("tcs", out object obj);
    var tcs = (TaskCompletionSource<bool>)obj;
    tcs.SetResult(chatStatus);
    return Task.CompletedTask;
    }
    Angular 4 client:
    // No change

    Error:- method not found while connecting signalr

    having error with signalr. On running application it is showing error "method not found".
    having problem in connection.
    I'm using signalr for chatting purpose. The project is in Reactjs and asp.net core.
    react app is created through creat-react-app (console).
    // code in reactjs*****
    import React, { Component } from 'react';
    import { HubConnection } from 'signalr-client-react';
    class SingnalR extends Component {
    constructor(props) {
    super(props);
    this.state = {
    bookingMessage: '',
    bookingHubConnection: null
    };
    }
    componentDidMount() {
    const bookingHubConnection = new HubConnection('http://localhost:5000/chatHub')
    this.setState({ bookingHubConnection }, () => {
    this.state.bookingHubConnection.start()
    .then(() => console.log('Signalr started '))
    .catch((err) => console.log('Error connecting signalr - ' + err));
    this.state.bookingHubConnection.on('booking', (message) => {
    const bookingMessage = message;
    this.setState({ bookingMessage });
    });
    });
    }
    render() {
    return (
    <div>
    <div>message from server {this.state.bookingMessage}</div>
    userName <input id="userName" />
    userMessage<input id="userMessage" />
    <button id = "sendMessage"> sendMessage</button>
    </div>
    )
    }
    }
    export default SingnalR;
    //code for asp.net core*******
    //code chatHub
    using Microsoft.AspNetCore.SignalR;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Threading.Tasks;
    namespace TinyHouseApi.SignalR
    {
    public class ChatHub:Hub
    {
    public async Task SendMessage(string user, string message)
    {
    await Clients.All.SendAsync("ReceiveMesage", user, message);
    }
    }
    }
    //code of Startupfile
    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.AddCors();
    services.AddDbContext<DataContext>(options => options.UseSqlServer(Configuration.GetConnectionString("testDB")));
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
    services.AddAutoMapper();
    //configure SignalR
    services.AddSignalR();
    // configure strongly typed settings objects
    var appSettingsSection = Configuration.GetSection("AppSettings");
    services.Configure<AppSettings>(appSettingsSection);
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
    // global cors policy
    app.UseCors(x => x
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader());
    app.UseAuthentication();
    app.UseMvc();
    //SignalR
    app.UseSignalR(routes =>
    {
    routes.MapHub<ChatHub>("/chatHub");
    });
    }
    }
    
    You use signalr-client-react witch depends on ms-signalr-client witch depends on jquery.signalR.js witch is the old version of signalR client and not compatible with ASP.Net Core SignalR.
    To use the latest SignalR version wit ASP.Net Core you should use #aspnet/signalr package. You cannot use signalr-client-react
    There is a tutorial here

    SignalR/Angular: Failed to load“url”.Response to preflight request doesn’t pass access control check.

    I am trying to implement a simple notification system using SignalR for my server, and Angular for my client. When I run my angular application after starting my server, I receive this error:
    Failed to load http://localhost:1874/notify/negotiate: Response to
    preflight request doesn't pass access control check: The value of the 'Access-
    Control-Allow-Credentials' header in the response is '' which must be 'true'
    when the request's credentials mode is 'include'. Origin 'http://localhost:4200'
    is therefore not allowed access. The credentials mode of
    requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
    I believe this may have something to do with cors? My server is just sending notifications and my client is displaying them. That is it. Right at the start up, my application is unable to connect to the server. Here is my startup.cs
    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    namespace SignalRHub
    {
    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.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
    {
    builder
    .AllowAnyMethod()
    .AllowAnyHeader()
    .WithOrigins("http://localhost:4200");
    }));
    services.AddSignalR();
    services.AddMvc();
    }
    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
    if (env.IsDevelopment())
    {
    app.UseDeveloperExceptionPage();
    }
    app.UseCors("CorsPolicy");
    app.UseSignalR(routes =>
    {
    routes.MapHub<NotifyHub>("/notify");
    });
    app.UseMvc();
    }
    }
    }
    And here is my Angular Component class:
    import { Component, OnInit } from '#angular/core';
    import { HubConnection, HubConnectionBuilder } from '#aspnet/signalr';
    import { Message } from 'primeng/api';
    #Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.css']
    })
    export class AppComponent implements OnInit {
    private _hubConnection: HubConnection;
    msgs: Message[] = [];
    constructor() { }
    ngOnInit(): void {
    this._hubConnection = new HubConnectionBuilder().withUrl('http://localhost:1874/notify').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({ severity: type, summary: payload });
    });
    }
    }
    Here is the github where I am following the tutorial from.
    https://github.com/rukshandangalla/Angular5-SignalR-Notifications
    Thank you.
    
    You will also need to allow credentials.
    To do so, change ConfigureServices, and add .AllowCredentials() like so:
    public void ConfigureServices(IServiceCollection services)
    {
    services.AddCors(o => o.AddPolicy("CorsPolicy", builder =>
    {
    builder
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials()
    .WithOrigins("http://localhost:4200");
    }));
    services.AddSignalR();
    services.AddMvc();
    }

    Error when accessing ASP.NET Core WebApi from Ionic

    I have some issues with calling my ASP.NET Core WebAPI from my Ionic app.
    I can see in the developer tools that the data get’s loaded correctly, but Ionic is giving me an error:
    error message from Ionic:
    data loaded from the api:
    CORS is enabled in the api:
    public class Startup
    {
    public void ConfigureServices(IServiceCollection services)
    {
    services.AddCors();
    services.AddDbContext<TodoContext>(opt =>
    opt.UseInMemoryDatabase("TodoList"));
    services.AddMvc()
    .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    }
    public void Configure(IApplicationBuilder app)
    {
    app.UseCors(builder => builder.WithOrigins("http://localhost"));
    app.UseMvc();
    }
    }
    I think the error is caused by Ionic or Angular. When I’m loading the data from a public api, everything works fine. I’ve also tried accessing the api with ssl and without.
    When you have any questions, feel free to ask me in the comments.
    Edit
    This is how I call the api:
    #Injectable()
    export class RestProvider {
    apiUrl = 'https://localhost:5001/api';
    constructor(public http: HttpClient) { }
    getTodoItems() {
    return new Promise(resolve => {
    this.http.get(this.apiUrl + '/todo').subscribe(data => {
    resolve(data);
    }, err => {
    console.log(err);
    });
    });
    }
    }
    and this is my controller:
    [Route("api/[controller]")]
    [ApiController]
    public class TodoController : ControllerBase
    {
    private readonly TodoContext _context;
    public TodoController(TodoContext context)
    {
    _context = context;
    if (_context.TodoItems.Count() == 0)
    {
    _context.TodoItems.Add(new TodoItem { Title = "Item1" });
    _context.TodoItems.Add(new TodoItem { Title = "Item2" });
    _context.SaveChanges();
    }
    }
    [HttpGet]
    public ActionResult<List<TodoItem>> GetAll()
    {
    return _context.TodoItems.ToList();
    }
    }
    
    fixed it by adding the port number:
    public void Configure(IApplicationBuilder app)
    {
    app.UseCors(builder => builder.WithOrigins("http://localhost:8100").AllowAnyMethod());
    app.UseMvc();
    }
    
    You can use the ionic.config.json file to configure a proxy in your app:
    {
    "name": "proxy-example",
    "app_id": "",
    "proxies": [
    {
    "path": "/api",
    "proxyUrl": "http://cors.api.com/api"
    }
    ]
    }
    Then when doing the http call:
    httpClient.get(proxyHost + '/api');
    More info Ionic Blog

    Angular 5 Post API Call

    I am very new to Angular , Developing an app in Angular 5 . I am trying to post some data to an API , below is my code
    .Net Core Web API
    [Produces("application/json")]
    [Route("api/Audit")]
    public class AuditController : Controller
    {
    private IConfiguration _configuration;
    private CommomUtility util;
    private Login Login;
    public AuditController(IConfiguration configuration)
    {
    _configuration = configuration;
    util = new CommomUtility(configuration);
    Login = new Login(configuration);
    }
    [HttpPost]
    public JsonResult Action([FromBody] List<Dictionary<string, string>> li)
    {
    DataTable dt = new DataTable();
    string jsonString = string.Empty;
    try
    {
    if (li[0]["ActionMethod"].Equals("CheckLogin", StringComparison.InvariantCultureIgnoreCase))
    {
    dt = Login.checkLogin(li);
    }
    }
    catch (Exception ex)
    {
    }
    finally
    {
    dt.TableName = "Result";
    jsonString = util.DataTableToJson(dt);
    }
    return Json(JObject.Parse(jsonString));
    }
    }
    Angular Login Componenet
    import { Component, OnInit } from '#angular/core';
    import { HttpClient,HttpClientModule,HttpParams,HttpHeaders } from '#angular/common/http';
    #Component({
    selector: 'app-login',
    templateUrl: './login.component.html',
    styleUrls: ['./login.component.css']
    })
    export class LoginComponent implements OnInit {
    username: string="";
    password: string="";
    loginBtnText: string='Log In';
    clearBtnText: string='Reset Fields';
    message:string;
    cssClass:string;
    constructor(private http:HttpClient ) { }
    ngOnInit() {
    }
    checkLogIn(){
    const params = new HttpParams();
    params.set('ActionMethod', 'CheckLogin');
    params.set('StaffCode', '15989');
    params.set('Password', '#####');
    var queryHeaders = new HttpHeaders();
    queryHeaders.append('Content-Type', 'application/json');
    debugger
    var v= this.http.post("http://localhost:57863/api/Audit/",
    params,{ headers: queryHeaders}
    )
    .subscribe(data =>
    {alert('ok');},
    error =>
    {alert("Error");}
    );
    }
    clearFields(){
    this.username="";
    this.password="";
    this.message="";
    }
    }
    I am invoking checkLogIn() on button click , after invoking this API it reach to constructor of API class only but does not go inside API Method.
    I checked my browser Network tab and it show
    415 Unsupported Media Type
    When I invoking the Get API (values api) which is by default comes in .Net Core Web API template than it works and show alert OK but failed in case of POST
    Update 1
    
    Seems like you have mentioned application/json in web API as Produces("application/json") but not passing it in header from the angular code.
    Try this
    import { HttpClient, HttpHeaders,HttpParams} from '#angular/common/http';
    if can't change the web api then change angular code as show below and keep the web api as it is.
    angular
    checkLogIn(){
    var requestData=[];
    var params={
    "ActionMethod":"CheckLogin",
    "StaffCode":"15989",
    "Password":"####"
    }
    requestData.push(params);
    const httpOptions = {
    headers: new HttpHeaders({
    'Content-Type': 'application/json'
    })
    };
    //pass it if you can't modify web api
    var v= this.http.post("http://localhost:5000/api/Audit/",
    requestData,httpOptions
    )
    .subscribe(data =>
    {alert('ok');},
    error =>
    {alert("Error");}
    );
    }
    if you can change web api then,
    angular
    checkLogIn(){
    var requestData=[];
    var params={
    "ActionMethod":"CheckLogin",
    "StaffCode":"15989",
    "Password":"####"
    }
    const httpOptions = {
    headers: new HttpHeaders({
    'Content-Type': 'application/json'
    })
    };
    //pass it like this if you can change web api
    var v= this.http.post("http://localhost:5000/api/Audit/",
    params,httpOptions
    )
    .subscribe(data =>
    {alert('ok');},
    error =>
    {alert("Error");}
    );
    }
    web api controller
    public class LoginContract
    {
    public string ActionMethod { get; set; }
    public string StaffCode { get; set; }
    public string Password { get; set; }
    }
    [HttpPost]
    public JsonResult Action([FromBody] LoginContract li)
    {
    DataTable dt = new DataTable();
    string jsonString = string.Empty;
    try
    {
    if (li.ActionMethod.Equals("CheckLogin", StringComparison.InvariantCultureIgnoreCase))
    {
    dt = Login.checkLogin(li);
    }
    }
    catch (Exception ex)
    {
    Console.Write(ex);
    }
    finally
    {
    dt.TableName = "Result";
    jsonString = util.DataTableToJson(dt);
    }
    return Json(JObject.Parse(jsonString));
    }
    I think you haven't enabled the Cors Module in your web api. add the following code to Startup.cs of your web api.
    If you haven't install the CORS nuget package
    Install-Package Microsoft.AspNetCore.Cors
    Add the code inside ConfigureServices method.
    services.AddCors(options =>
    {
    options.AddPolicy("AllowAll",
    builder =>
    {
    builder
    .AllowAnyOrigin()
    .AllowAnyMethod()
    .AllowAnyHeader()
    .AllowCredentials();
    });
    });
    Now in Configure method add the following code before app.UseMvc().
    app.UseCors("AllowAll");
    I hope this will fix your problem. If you have any issues or doubt let me know.
    
    Error 415 Unsupported media type Saying that the value of request header content-type is not what server is expecting in the request. Try to set content-type header to value application/json in angular.
    
    The content-type seems to be wrong. You can try to send a JSON object as the payload directly.
    `
    const payload =
    {'ActionMethod': 'CheckLogin',
    'StaffCode': '15989',
    'Password': 'a$a#'
    }
    var v= this.http.post("http://localhost:57863/api/Audit/",payload)`
    
    You are facing COARS errors problem very famous
    as u invoking another processes link hitting so causes dont panic
    Do
    webapiconfig.cs
    var cors = new System.Web.Http.Cors.EnableCorsAttribute("http://localhost:51156",
    "*", "*");
    config.EnableCors(cors);
    // ADD JUST THIS LINE TO REGISTER FOLLOWING CLASS.
    config.Formatters.Add(new BrowserJsonFormatter());
    now add following code to ovverride
    // TO SEE DATA IN JSON IN CHROME BROWSER ADD FOLLOWING CLASS BrowserJsonFormatter and REGISTER IN METHOD ADD NEW OBJECT OF THIS CLASS.
    public class BrowserJsonFormatter : System.Net.Http.Formatting.JsonMediaTypeFormatter
    {
    public BrowserJsonFormatter()
    {
    this.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
    this.SerializerSettings.Formatting = Formatting.Indented;
    }
    public override void SetDefaultContentHeaders(Type type, HttpContentHeaders headers, MediaTypeHeaderValue mediaType)
    {
    base.SetDefaultContentHeaders(type, headers, mediaType);
    headers.ContentType = new MediaTypeHeaderValue("application/json");
    }
    }
    //-----------------------------------------------------------------------------------------------------------------------

    • Remove From My Forums
    • Question

    • Hi All, 

      My Lync federation to Lync Online users has stopped working. My edge server has the following Error in the event logs:

      Error
      Event ID: 14428

      TLS outgoing connection failures. Over the past 12 minutes, Lync Server has experienced TLS outgoing connection failures 15 time(s). The error code of the last failure is 0x80072746 while trying to connect to the server "sipfed.online.lync.com" at address [66.119.157.212:5061], and the display name in the peer certificate is "sipfed.online.lync.com". Cause: Most often a problem with the peer certificate or perhaps the host name (DNS) record used to reach the peer server. Target principal name is incorrect means that the peer certificate does not contain the name that the local server used to connect. Certificate root not trusted error means that the peer certificate was issued by a remote CA that is not trusted by the local machine. Resolution: Check that the address and port matches the FQDN used to connect, and that the peer certificate contains this FQDN somewhere in its subject or SAN fields. If the FQDN refers to a DNS load balanced pool then check that all addresses returned by DNS refer to a server in the same pool. For untrusted root errors, ensure that the remote CA certificate chain is installed locally. If you have already installed the remote CA certificate chain, then try rebooting the local machine.

      and the following from the SipStack trace:

      TL_ERROR(TF_CONNECTION) [0]0A38.0C58::05/07/2015-00:10:11.840.00018488 (SIPStack,SIPAdminLog::WriteConnectionEvent:SIPAdminLog.cpp(460))[3093861427] 
      $$begin_record
      Severity: error
      Text: Connection was closed because a send operation failed
      Local-IP: 103.5.28.177:49165
      Peer-IP: 66.119.157.212:5061
      Peer: sipfed.online.lync.com:5061
      Connection-ID: 0x1201
      Transport: M-TLS
      Result-Code: 0x80072746
      Data: fqdn="sipfed.online.lync.com:5061";ip-address="66.119.157.212";peer-type="FederatedPartner";winsock-code="10054";winsock-info="The peer forced closure of the connection"
      $$end_record

      My certificate is valid and current (DigiCert) so I have no idea what is going wrong. Any help appreciated


      Thanks Christoph

    Answers

    • OK it is definitely a M$ certificate issue.

      I forced sipfed.online.lync.com to resolve to 132.245.162.21 via hosts file, restarted edge lync services and everything works, using 66.119.157.212 breaks it again.


      Thanks Christoph

      • Marked as answer by

        Thursday, May 7, 2015 4:17 AM

    Понравилась статья? Поделить с друзьями:
  • Error failed to build gem native extension ruby
  • Error failed to build gem native extension error failed to build gem native extension
  • Error failed to apply push options failed to open tun tap interface
  • Error failed to add operation for get api v1 connections
  • Error failed sending 1072 bytes