programing

signalR : /signalr/hubs가 생성되지 않음

codeshow 2023. 10. 14. 10:47
반응형

signalR : /signalr/hubs가 생성되지 않음

튜토리얼은 새로운 프로젝트에서는 작동할 수 있지만 기존 프로젝트에서는 작동할 수 없습니다.

제 프로젝트는 ASP 입니다.web.config 파일에서 다음 속성을 가진 Net MVC 4 웹 응용 프로그램:

<appSettings>
  <add key="webpages:Enabled" value="true"/>
</appSettings>

이것은 내 애플리케이션이 Angular를 사용하는 Single-Page-Application이기 때문입니다.고객측의 JS.응용 프로그램의 유일한 페이지는 index.cshtml이며, 여기에 signalR에 대한 관련 코드를 추가했습니다.

 <!-- signalR chat -->
<script src="~/Scripts/jquery.signalR-1.0.0.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="/signalr/hubs"></script>
<!--Add script to update the page and send messages.--> 
<script type="text/javascript">
    $(function () {
        // Declare a proxy to reference the hub. 
        var chat = $.connection.chatHub;
        // Create a function that the hub can call to broadcast messages.
        chat.client.broadcastMessage = function (name, message) {
            // Html encode display name and message. 
            var encodedName = $('<div />').text(name).html();
            var encodedMsg = $('<div />').text(message).html();
            // Add the message to the page. 
            $('#discussion').append('<li><strong>' + encodedName
                + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
        };
        // Get the user name and store it to prepend to messages.
        $('#displayname').val(prompt('Enter your name:', ''));
        // Set initial focus to message input box.  
        $('#message').focus();
        // Start the connection.
        $.connection.hub.start().done(function () {
            $('#sendmessage').click(function () {
                // Call the Send method on the hub. 
                chat.server.send($('#displayname').val(), $('#message').val());
                // Clear text box and reset focus for next comment. 
                $('#message').val('').focus();
            });
        });
    });
</script>

그럼 ChatHub.cs 파일을 확보했습니다.

public class ChatHub : Hub
{
    public void Send(string name, string message)
    {
        // Call the broadcastMessage method to update clients.
        Clients.All.broadcastMessage(name, message);
    }
}

그리고 마침내 전세계적으로.asax:

 protected void Application_Start()
    {
        RouteTable.Routes.MapHubs();
        BundleConfig.RegisterBundles(BundleTable.Bundles);
    }

응용 프로그램을 실행하면 /signalr/hubs 파일이 생성되지 않습니다.파일을 요청할 때 404를 받게 되는데, 이 파일은 회선상에서 충돌합니다.

 chat.client.broadcastMessage = function (name, message) { ....

이전 줄에서 chatHub을 찾지 못했기 때문에 chat이 null이기 때문입니다.

var chat = $.connection.chatHub;

내 코드에 무슨 문제가 있는지 아는 사람?

갱신하다

다음 줄을 변경하여 문제를 해결했습니다.

<script src="/signalr/hubs"></script>

로.

<script src="~/signalr/hubs"></script>

다음 줄을 변경하여 문제를 해결했습니다.

<script src="/signalr/hubs"></script>

로.

<script src="~/signalr/hubs"></script>

또한 /signalr/hubs가 생성되지 않는 이유는 OWIN Startup Configuration에서 신호R을 매핑하는 것을 잊었기 때문입니다.

public class Startup
{
   public void Configuration(IAppBuilder appBuilder){
         ...
         appBuilder.MapSignalR();
         ...
   }
 ...

저의 경우, 채팅허브 수업이 공개로 표시되지 않았기 때문입니다.

허브 파일이 생성되지 않는 비슷한 문제가 있었습니다.OP가 여기서 절차를 따랐던 것 같습니다.제가 문제를 해결한 방법은 jquery와 관련된 것입니다.아래에 링크한 튜토리얼은 jquery 1.6.4와 jquery-signalr 버전 2.1.0으로 작성되었습니다.Visual Studio에서 Scripts 폴더를 생성할 때 jquery version 1.10.2와 jquery-signalr version 2.0.2를 사용했습니다.

제가 수정한 방법은 단순히 index.html 파일을 편집하는 것이었습니다.Chrome의 javascript 콘솔 창 Ctrl+Shift+J를 사용하여 오류를 확인할 수 있습니다.

저에게 해결책은 모든 패키지를 다시 설치하고 모든 종속 요소를 복원하는 것이었습니다.

nuget powershell 콘솔을 열고 이 명령을 사용합니다.

Update-Package -Reinstall

시그널 R Readme 파일에 이 문제에 대한 몇 가지 참고 사항이 있음을 덧붙이고 싶습니다.또한 신호 R 페이지가 PartialView에 있는 경우 마스터 페이지에 일부 스크립트를 배치해야 합니다.

Please see http://go.microsoft.com/fwlink/?LinkId=272764 for more information on using SignalR.

Upgrading from 1.x to 2.0
-------------------------
Please see http://go.microsoft.com/fwlink/?LinkId=320578 for more information on how to 
upgrade your SignalR 1.x application to 2.0.

Mapping the Hubs connection
----------------------------
To enable SignalR in your application, create a class called Startup with the following:

using Microsoft.Owin;
using Owin;
using MyWebApplication;

namespace MyWebApplication
{
    public class Startup
    {
        public void Configuration(IAppBuilder app)
        {
            app.MapSignalR();
        }
    }
} 

Getting Started
---------------
See http://www.asp.net/signalr/overview/getting-started for more information on how to get started.

Why does ~/signalr/hubs return 404 or Why do I get a JavaScript error: 'myhub is undefined'?
--------------------------------------------------------------------------------------------
This issue is generally due to a missing or invalid script reference to the auto-generated Hub JavaScript proxy at '~/signalr/hubs'.
Please make sure that the Hub route is registered before any other routes in your application.

In ASP.NET MVC 4 you can do the following:

      <script src="~/signalr/hubs"></script>

If you're writing an ASP.NET MVC 3 application, make sure that you are using Url.Content for your script references:

    <script src="@Url.Content("~/signalr/hubs")"></script>

If you're writing a regular ASP.NET application use ResolveClientUrl for your script references or register them via the ScriptManager 
using a app root relative path (starting with a '~/'):

    <script src='<%: ResolveClientUrl("~/signalr/hubs") %>'></script>

If the above still doesn't work, you may have an issue with routing and extensionless URLs. To fix this, ensure you have the latest 
patches installed for IIS and ASP.NET. 

내 경우엔 내가 실종됐었소

        app.MapSignalR();

인에public void Configuration(IAppBuilder app)s 에 .

처음부터 확장을 시작하는 사람들을 위한 몇 가지 조언이 있습니다.제 경우에는 원격 클라이언트를 작업하는 중이었는데, 그 사실을 전혀 깨닫지 못했습니다.

A. 자습서 예에서는 웹 앱(서버) 시작을 사용 설명문에 나열하며, 그 후 웹 앱이 제대로 배치되고 더 이상 존재하지 않습니다.

사용명세서를 없앴고 나중에 폐기하기 위해 웹앱을 참고하였습니다.

B. 클라이언트의 URL이 서버와 다릅니다.이 예는 동일한 URL을 가진 signalr 서버에 의존합니다. "/ signalr/ hubs"는 signalr 서버가 실행하는 엔드포인트로, signalr 클라이언트가 서버가 구현하는 모든 허브의 스크립트를 가져오기 위해 호출합니다.

클라이언트에 상대적으로 만들지 말고 "http://myServerURL/signalr/hubs"를 포함해야 합니다.

거짓말은 안됩니다.이것은 2주 동안 안정적으로 나를 좌절시켰는데, 왜냐하면 어떤 마법에 의해 해결책이 동료의 설정에서 어쨌든 작동했기 때문입니다.이로 인해 컴퓨터에서 연결을 차단하고 있었을 IIS 설정과 방화벽 설정 및 CORS 설정을 계속 찾게 되었습니다.마지막 스택 오버플로 질문을 모두 지웠습니다. 그리고 궁극적인 대답은 처음부터 웹 앱에 하트비트 모니터를 구현했어야 한다는 것이었습니다.

행운을 빌어요 그리고 이것이 다른 사람들의 시간을 절약할 수 있기를 바랍니다.

보시기Microsoft.Owin.Host.Systemwebnuget package가 설치되지 않았으므로 동적 jslib을 구축하지 않습니다.

Owin Startup 미발화

언급URL : https://stackoverflow.com/questions/17422023/signalr-signalr-hubs-is-not-generated

반응형