locked
SignalR didnt work RRS feed

  • Question

  • User1587595710 posted

    I'm worried... This SignalR tutorial is so easy, but athe the same time, didnt work... Can anyone know why?? In the sendbutton didnt call the Post Method

    @{
        ViewData["Title"] = "Message";
    }
    
    <p>User conneting: @ViewBag.sessionv</p>
    
    <h1>Message</h1>
    
    @using (Html.BeginForm("Message", "User", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
        <div class="row">
            <div class="col-md-4">
                <div class="row">
                    <div class="col-2">User</div>
                    <div class="col-4"><input type="text" id="userInput" /></div>
                </div>
                <div class="row">
                    <div class="col-2">Message</div>
                    <div class="col-4"><input type="text" id="messageInput" /></div>
                </div>
                <div class="row">
                    <input type="file" value="Select File" name="file">
                </div>
                <div class="row">
                    <div class="col-6">
                        <input type="submit" id="sendButton" value="Send Message" />
                    </div>
                </div>
                <div class="row">
                    <textarea readonly rows="13" id="messagesList"></textarea>
                </div>
            </div>
        </div>
    }
    
    <script src="~/js/signalr/dist/browser/signalr.js"></script>
    <script src="~/js/chat.js"></script>

    Controller

            private readonly IHubContext<ChatHub> chatHub;
            public UserController(IHubContext<ChatHub> hubContext)
            {
                this.chatHub = hubContext;
            }
    
            [HttpPost]
            public async Task<ActionResult> Message(Message message, IFormFile file)
            {
    //Some code
                await chatHub.Clients.All.SendAsync("ReceiveMessage", message.emisor, message.Text);
    //Other code
                return View();
            }

    Chat.js

    var connection = new signalR.HubConnectionBuilder().withUrl("/chatHub").build();
    
    connection.on("ReceiveMessage", function (user, message) {
        const msg = message.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
        const encodedMsg = user + " says " + msg;
        const li = document.createElement("li");
        li.textContent = encodedMsg;
        document.getElementById("messagesList").appendChild(li);
    });
    
    connection.start().catch(error => console.error(err.toString()));
    
    document.getElementById("sendButton").addEventListener("click", function (event) {
        const user = document.getElementById("userInput").value;
        const message = document.getElementById("messageInput").value;
        connection.invoke("SendMessage", user, message).catch(function (err) {
            return console.error(err.toString());
        });
        event.preventDefault();
    });

    ChatHub.cs

    using Microsoft.AspNetCore.SignalR;
    using System.Threading.Tasks;
    
    namespace MRDB
    {
        public class ChatHub : Hub
        {
            public async Task SendMessage(string name, string message)
            {
                await Clients.All.SendAsync("ReceiveMessage", name, message);
            }
        }
    }

    And the startup

    using Microsoft.AspNetCore.Builder;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.Extensions.Configuration;
    using Microsoft.Extensions.DependencyInjection;
    using Microsoft.Extensions.Hosting;
    
    namespace MRDB
    {
        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.AddControllersWithViews();
                services.AddMemoryCache();
                services.AddSession();
                services.AddSignalR();
            }
    
            // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
            public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
            {
                if (env.IsDevelopment())
                {
                    app.UseDeveloperExceptionPage();
                }
                else
                {
                    app.UseExceptionHandler("/Home/Error");
                    // 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.UseStaticFiles();
                app.UseSession();
    
                app.UseRouting();
    
                app.UseAuthorization();
                app.UseCookiePolicy();
    
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapControllerRoute(
                        name: "default",
                        pattern: "{controller=Home}/{action=Index}/{id?}");
                    endpoints.MapHub<ChatHub>("/chatHub");
                });
            }

    So I watch this tutorial => SignalR on spanish 

    And the Microsoft tutorial => Get started

    And, at the time to press the button, didnt call the Post

    Saturday, November 28, 2020 2:54 AM

All replies

  • User197322208 posted

    Do you have an error in the browser console ? (F12)

    Sunday, November 29, 2020 9:41 AM
  • User1587595710 posted

    Do you have an error in the browser console ? (F12)

    No I dont, I discover that if I delete the id="sendButton" on the button, it call the post Method, but didnt call the signalR clases... So, if I delete the id of the button, call the post method, but no the signalR(get error on the line where I call the chatHub, saying that theres no client connected)... If stay, call the signalR but not the controller

    Tuesday, December 1, 2020 4:38 PM
  • User197322208 posted

    The code has

     message.emisor, message.Text

    From which inputs in the form should those fields come?

    Monday, December 14, 2020 7:41 AM
  • User1587595710 posted

    From a variable type class

    Tuesday, December 15, 2020 3:55 PM
  • User197322208 posted

    This comes from here - so should be on the the HTML 

     [HttpPost]
            public async Task<ActionResult> Message(Message message, IFormFile file)
    Wednesday, December 16, 2020 2:39 PM