SignalR在MVC3中触发客户端事件

时间:2012-08-28 15:55:08

标签: c# jquery asp.net-mvc asp.net-mvc-3 signalr

我有一个发票导入器中心,如下所示:

public class ImporterHub : Hub, IDisconnect, IConnected
{

    public void InvoiceImported(InvoiceImportedMessage message)
    {
        Clients["importer"].InvoiceImported(message);
    }

    public void FileImported(FileImportedMessage message)
    {
        Clients["importer"].FileImported(message);
    }

    public System.Threading.Tasks.Task Disconnect()
    {
        return Clients["importer"].leave(Context.ConnectionId, DateTime.Now.ToString());
    }

    public System.Threading.Tasks.Task Connect()
    {
        return Clients["importer"].joined(Context.ConnectionId, DateTime.Now.ToString());
    }

    public System.Threading.Tasks.Task Reconnect(IEnumerable<string> groups)
    {
        return Clients["importer"].rejoined(Context.ConnectionId, DateTime.Now.ToString());
    }
}

在我的控制器中,我正在为长时间运行的导入过程捕获事件,如下所示:

    [HttpPost]
    public ActionResult Index(IndexModel model)
    {
        if (ModelState.IsValid)
        {
            try
            {
                model.NotificationRecipient = model.NotificationRecipient.Replace(';', ',');
                ImportConfiguration config = new ImportConfiguration()
                {
                    BatchId = model.BatchId,
                    ReportRecipients = model.NotificationRecipient.Split(',').Select(c => c.Trim())
                };
                var context = GlobalHost.ConnectionManager.GetHubContext<ImporterHub>();
                context.Groups.Add(this.Session.SessionID, "importer");
                System.Threading.ThreadPool.QueueUserWorkItem(foo => LaunchFileImporter(config));
                Log.InfoFormat("Queued the ImportProcessor to process invoices.  Send Notification: {0} Email Recipient: {1}",
                    model.SendNotification, model.NotificationRecipient);
                TempData["message"] = "The import processor job has been started.";
                //return RedirectToAction("Index", "Home");
            }
            catch (Exception ex)
            {
                Log.Error("Failed to properly queue the invoice import job.", ex);
                ModelState.AddModelError("", ex.Message);
            }
        }

    private void LaunchFileImporter(ImportConfiguration config)
    {
        using (var processor = new ImportProcessor())
        {
            processor.OnFileProcessed += new InvoiceFileProcessing(InvoiceFileProcessingHandler);
            processor.OnInvoiceProcessed += new InvoiceSubmitted(InvoiceSubmittedHandler);
            processor.Execute(config);
        }
    }

    private void InvoiceSubmittedHandler(object sender, InvoiceSubmittedEventArgs e)
    {
        var context = GlobalHost.ConnectionManager.GetHubContext<ImporterHub>();
        var message = new InvoiceImportedMessage()
        {
            FileName = e.FileName,
            TotalErrorsInFileProcessed = e.TotalErrors,
            TotalInvoicesInFileProcessed = e.TotalInvoices
        };
        context.Clients["importer"].InvoiceImported(message);
    }
    private void InvoiceCollectionSubmittedHandler(object sender, InvoiceCollectionSubmittedEventArgs e)
    {
    }
    private void InvoiceFileProcessingHandler(object sender, InvoiceFileProcessingEventArgs e)
    {
        var context = GlobalHost.ConnectionManager.GetHubContext<ImporterHub>();
        var message = new FileImportedMessage()
        {
            FileName = e.FileName
        };
        context.Clients["importer"].FileImported(message);
    }

我在导视台的视图中有以下脚本:

<script type="text/javascript">
    jQuery.connection.hub.logging = true;
    var importerHub = jQuery.connection.importerHub;

    importerHub.InvoiceImported = function (message) {
        jQuery('#' + message.FileName + '_Invoices').text(message.TotalInvoicesInFileProcessed);
        jQuery('#' + message.FileName + '_Errors').text(message.TotalErrorsInFileProcessed);
    };

    importerHub.FileImported = function (message) {
        jQuery('#' + message.FileName + '_Processed').text('Done');
    };

    jQuery.connection.hub.start();
</script>

我期望发生的事情:

我当时希望触发服务器端事件,这会将消息发送到客户端, 反过来,它会触发事件以更新导入过程的状态。

似乎正在发生的事情:

所有服务器端事件都触发,一切都很好。 signalR库似乎正确初始化,但事件从未触发,我从未得到更新显示在屏幕上。

我做错了什么?这是我第一次尝试使用signalR库,所以我完全有可能做错了。

1 个答案:

答案 0 :(得分:1)

相信你的问题是你的客户端集线器事件是用init-caps命名的,而SignalR的默认行为是在发布到客户端时将它们转换为init-lower以与common对齐JavaScript约定。尝试将您的中心事件注册更改为:

importerHub.invoiceImported = function (message) { 

importerHub.fileImported = function (message) {