来自Controller的C#SignalR推送通知实时无效

时间:2017-02-28 10:32:38

标签: c# asp.net notifications signalr real-time

我一直在尝试在服务器上运行几个过程代码,我使用参数放在表单上并使用MVC Controller执行。我希望被调用的控制器上的每一步(方法/功能)都能实时向客户端Web更新信息。

我一直在尝试使用SignalR将实时推送通知/信息更新到客户端,它与客户端触发器一起工作但是当我尝试从控制器调用集线器时它才能正常工作。

这是我的控制器代码:

<h2>Index</h2>


@Ajax.BeginForm("data", "Home", FormMethod.Post, null) {
<div class="input-group">
    <span>Apa Aja</span>
    @Html.EditorFor(model => model.apaAja, new { htmlhtmlAttributes = new { @id = "apaAja" } })
</div>
<div class="input-group">
    <span> Boleh </span>
    @Html.EditorFor(model => model.boleh, new { htmlhtmlAttributes = new { @id = "boleh" } })
</div>
<button id="subm" type="submit">Submit</button>

<div id="container">
</div>
@section scripts{
    <script src="~/Scripts/jquery.unobtrusive-ajax.js"></script>
    <script src="~/Scripts/jquery.signalR-2.2.1.min.js"></script>
    <script src="~/signalr/hubs"></script>
    <script>
        $(document).ready(function () {
            var c = $.connection.myHub1;
            c.client.messageSend = function (message) {

                var encodedMsg = $('<div />').text(message).html();
                // Add the message to the page.
                $('#container').append('<li> < strong >' + 'Info Message :  ' +
                    '</strong >:&nbsp;&nbsp; ' + encodedMsg + '</li >');
            };

        $.connection.hub.start();

        });
    </script>

这是我的客户代码:

namespace SignalR1.Hubs
{
    public class MyHub1 : Hub
    {
        public void Message(string message)
        {
            Clients.All.messageSend(message);
        }
    }
}

这是我的Hub类:

private String pictureImagePath = "";

private void openBackCamera() {

String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

String imageFileName = timeStamp + ".jpg";

File storageDir = Environment.getExternalStoragePublicDirectory(
        Environment.DIRECTORY_PICTURES);

pictureImagePath = storageDir.getAbsolutePath() + "/" + imageFileName;

File file = new File(pictureImagePath);

Uri outputFileUri = Uri.fromFile(file);

Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);               

cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, outputFileUri);

startActivityForResult(cameraIntent, 1);}

1 个答案:

答案 0 :(得分:1)

您有一个名为messageSend的客户端回调,然后在您的集线器中正确拥有Clients.All.messageSend,但是当您使用GlobalHost.ConnectionManager.GetHubContext时,您正在访问集线器上下文而不是集线器类本身。

所以改成它:

        var hub = GlobalHost.ConnectionManager.GetHubContext<Hubs.MyHub1>();
        //you don't actually have access to the MyHub1 class at this point
        // instead of
        // hub.Clients.All.Message(data.apaAja);
        // you need
        hub.Clients.All.messageSend(data.apaAja);

实际上,使用此机制时,hub类方法变得有点多余。我通常使用集线器类来管理连接和客户端使用覆盖的覆盖等...