signalR

c# file

using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.SignalR;


namespace ResumeManager.Controllers

{

    public class ChatHub : Hub

    {

        public async Task SendMessage(string user, string message)

        {

            await Clients.All.SendAsync("ReceiveMessage", user, message);

        }

    }

}

----- startup .cs below 5 version
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.DependencyInjection;

namespace ChatApp
{
    public class Startup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddSignalR(); // Add SignalR service
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();
            app.UseStaticFiles(); // Allow serving static files

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapHub<ChatHub>("/chatHub"); // Map the SignalR hub
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller=Home}/{action=Index}/{id?}");
            });
        }
    }
}

--above 6 version program.cs
using Microsoft.AspNetCore.Authentication.Negotiate;
using Microsoft.EntityFrameworkCore;
using ResumeManager.Controllers;
using ResumeManager.Data;

var builder = WebApplication.CreateBuilder(args);

var connectionString = builder.Configuration.GetConnectionString("DbConn");

builder.Services.AddDbContext<ResumeDBContext>(options =>
   options.UseSqlServer(connectionString));


// Add services to the container.
builder.Services.AddControllersWithViews();

builder.Services.AddAuthentication(NegotiateDefaults.AuthenticationScheme)
   .AddNegotiate();

builder.Services.AddAuthorization(options =>
{
    // By default, all incoming requests will be authorized according to the default policy.
    options.FallbackPolicy = options.DefaultPolicy;
});
builder.Services.AddRazorPages();
builder.Services.AddSignalR(); // Add SignalR service

var app = builder.Build();

// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
    app.UseExceptionHandler("/Home/Error");
}
app.MapHub<ChatHub>("/chatHub"); // Map the SignalR hub
app.UseStaticFiles();


app.UseRouting();

app.UseAuthentication();
app.UseAuthorization();

app.MapControllerRoute(
    name: "default",
    pattern: "{controller=Home}/{action=Index}/{id?}");

app.Run();

------view with cdcn--

<!DOCTYPE html>
<html>
<head>
    <title>Chat App</title>
</head>
<body>
    <input type="text" id="userInput" placeholder="Enter your name" />
    <input type="text" id="messageInput" placeholder="Enter your message" />
    <button id="sendButton">Send</button>
    <ul id="messageList"></ul>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/microsoft-signalr/7.0.10/signalr.min.js"></script>
    <script>
        const connection = new signalR.HubConnectionBuilder()
            .withUrl("/chatHub")
            .build();

        connection.on("ReceiveMessage", (user, message) => {
            const messageList = document.getElementById("messageList");
            const li = document.createElement("li");
            li.textContent = `${user}: ${message}`;
            messageList.appendChild(li);
        });

        document.getElementById("sendButton").addEventListener("click", () => {
            const userInput = document.getElementById("userInput");
            const messageInput = document.getElementById("messageInput");

            const user = userInput.value;
            const message = messageInput.value;

            connection.invoke("SendMessage", user, message);

            userInput.value = "";
            messageInput.value = "";
        });

        connection.start().catch(err => console.error(err.toString()));
    </script>
</body>
</html>

Comments