Click here to Skip to main content
15,887,585 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi everyone, who can help me why cannot connect to server side from client side? keep showing "Response status code does not indicate success: 404 (not found)"

What I have tried:

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.Http;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;
using WebApplication10.Hubs;

namespace WebApplication10
{
    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 ConfigurationServices(IServiceCollection services)
        {
            services.AddMvcCore().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddSignalR();
        }

        //This method gets called by the runtime. Use this method to configure the HTTP requerst pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }
            
            app.UseHttpsRedirection();
            app.UseSignalR(routes =>
            { 
                routes.MapHub<TestHub>("/testHub");
            });
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                name: "default",
                template: "{controller=Authorization}/{action=HelloWorld}")
            });
        }
    }
}


TestHub.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;


namespace WebApplication10.Hubs
{
    public class TestHub : Hub
    {
        public override bool Equals(object obj)
        {
            return base.Equals(obj);
        }

        public override int GetHashCode()
        {
            return base.GetHashCode();
        }

        public override Task OnConnectedAsync()
        {
            Clients.Caller.SendAsync("Connected", Context.ConnectionId);
            return base.OnConnectedAsync();
        }

        public override Task OnDisconnectedAsync(Exception exception)
        {
            return base.OnDisconnectedAsync(exception);
        }

        public override string ToString()
        {
            return base.ToString();
        }

        protected override void Dispose(bool disposing)
        {
            base.Dispose(disposing);
        }
    }
}


ValuesController.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using WebApplication10.Hubs;


namespace WebApplication10.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class ValuesController : ControllerBase
    {
        
        IHubContext<TestHub> _hubContext;
        public ValuesController(IHubContext<TestHub> hubContext)
        {
            _hubContext = hubContext;
        }

        //Get api/values
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            return new string[] { "value1", "value2" };
        }

        //Get api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }

        //POST api/values
        [HttpPost]
        public void Post([FromBody] string value)
        {
            _hubContext.Clients.All.SendAsync("Posted", value);
        }

        //PUT api/value/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        //DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}


MainWindow.xaml.cs
using Microsoft.AspNetCore.SignalR.Client;
using System;
using System.Threading.Tasks;
using System.Windows;

namespace WpfApp1
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private HubConnection _connection;
        public MainWindow()
        {
            InitializeComponent();

            _connection = new HubConnectionBuilder()
                .WithUrl("http://localhost:8081/api/")
                .Build();
            _connection.Closed += async (error) =>
            {
                await Task.Delay(new Random().Next(0, 5) * 1000);
                await _connection.StartAsync();
            };
        }

        private async void BtnConnect_Click(object sender, RoutedEventArgs e)
        {
            
            _connection.On<string>("Connected",
                                    (connectionid) =>
                                    {
                                        //MessageBox.Show(connectionid);
                                        tbMain.Text = connectionid;
                                    });
            
            _connection.On<string>("Posted",
                                    (value) =>
                                    {
                                    Dispatcher.BeginInvoke((Action)(() =>
                                    { 
                                        messageList.Items.Add(value);
                                    }));
                                    });
            
            try
            {
                await _connection.StartAsync();
                messageList.Items.Add("Connection started");
                btnConnect.IsEnabled = false;
            }
            catch(Exception ex)
            {
                messageList.Items.Add(ex.Message);
            }
            
        }
    }
}
Posted
Updated 29-Oct-19 23:11pm

1 solution

I had a similar problem that strangely occurred on some computers: the first try fails and the second try works.
Never found the cause but "solved" it by adding a retry.
It also baffles me that there is so little information about these sort of Signal problems on the internet.

You might be interested in: Diagnostics Guide · aspnet/SignalR Wiki · GitHub[^]

Here is some code to give you an idea how the retry mechanism works, it is not a full example as I can not disclose the unencryption routines used:
/// <summary>
/// SignalR client proxy.
/// </summary>
private IHubProxy HubProxy { get; set; }

/// <summary>
/// The number of retries for a SignalR request.
/// </summary>
private int signalRretries;

this.signalRretries = 0;
this.SendXmlRequest();


SendXmlRequest()
{
	if (this.hubConnection == null || this.hubConnection.State == ConnectionState.Disconnected)
	{
		// Connect to SignalR server using a 30 second timeout.
		Connect(30000, SignalrServerUri);
	}

	if (this.hubConnection.State != ConnectionState.Connected)
	{
		this.ShowError("Connection to SignalR server failed !");
		this.Cursor = Cursors.Default;
	}
	else
	{
		HubProxy.Invoke("Send", UserName, requestEncrypt);
	}
}

/// <summary>
/// Creates and connects the SignalR hub connection and hub proxy.
/// Fires AddMessageReceived() on SignalR server event.
/// </summary>
/// <param name="timeoutMs">The timeout period in milliseconds.</param>
private bool Connect(int timeoutMs, string serverUri)
{
	this.hubConnection = new HubConnection(serverUri);
	this.hubConnection.Closed += Connection_Closed;
	this.HubProxy = hubConnection.CreateHubProxy("SignalrHub");

	// Handle incoming event with xml reply from SignalR server.
	this.HubProxy.On<string, string>("AddMessage", this.AddMessageReceived);
	this.hubConnection.Start().Wait(timeoutMs);
}

/// <summary>
/// Handle incoming SignalR event from server and disconnect SignalrHub connection.
/// </summary>
/// <param name="name">The name (optional).</param>
/// <param name="xmlEncryptedReply">The encrypted xml reply.</param>
private void AddMessageReceived(string name, string xmlEncryptedReply)
{
	if (this.InvokeRequired)
	{
		this.Invoke(new Action(() => AddMessageReceived(name, xmlEncryptedReply)));
	}
	else
	{
		this.hubConnection.Closed -= Connection_Closed;
		this.hubConnection.Stop();

		// Do some string checking
		var message = this.ProcessXmlReply(license, xmlEncryptedReply);

		if (string.IsNullOrEmpty(message) || message.Equals(@"Reply is not valid"))
		{
			// For some unknown reason first try always fails ...
			signalRretries++;
	
			if (signalRretries < 3)
			{
				this.SendXmlRequest();
			}
		}
	}
}
 
Share this answer
 
v3
Comments
gan chee siang 30-Oct-19 21:24pm    
How u solve it?
gan chee siang 30-Oct-19 21:34pm    
how u solve this problem?
gan chee siang 30-Oct-19 21:39pm    
This error message is shown in the WPF console application

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900