从 MVC 动作中使用 signalR hub

Using signalR hub from MVC action

this tutorial 之后,我试图显示一个长操作中各个步骤的进度。我能够根据示例成功地模拟 集线器内的长时间操作,每一步都将更新报告回客户端。

更进一步,我现在想显示在具有 [HttpPost] 属性的 MVC 操作方法中发生的实时、长 运行 进程的状态。

问题是我似乎无法从集线器上下文更新客户端。我意识到我必须创建一个集线器上下文才能使用集线器进行通信。我知道的一个区别是我必须使用 hubContext.Clients.All.sendMessage(); VS。 hubContext.Clients.Caller.sendMessage(); 示例中列出。根据我在 ASP.NET SignalR Hubs API Guide - Server 中的发现 我应该能够按照示例中的说明使用 Clients.Caller,但我仅限于在集线器 class 中使用它。主要是想弄明白为什么action方法收不到信号

非常感谢您的帮助。

我已经像这样创建了我的 OWIN Startup() class...

using System;
using System.Threading.Tasks;
using Microsoft.Owin;
using Owin;

[assembly: OwinStartup(typeof(HL7works.Startup))]

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

我的hub是这样写的...

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;

namespace HL7works
{
    public class ProgressHub : Hub
    {
        public string msg = string.Empty;
        public int count = 0;

        public void CallLongOperation()
        {
            Clients.Caller.sendMessage(msg, count);
        }
    }
}

我的控制器...

// POST: /Task/ParseToExcel/
[HttpPost]
public ActionResult ParseToExcel(HttpPostedFileBase[] filesUpload)
{
    // Initialize Hub context
    var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();
    hubContext.Clients.All.sendMessage("Initalizing...", 0);

    double fileProgressMax = 100.0;
    int currentFile = 1;
    int fileProgress = Convert.ToInt32(Math.Round(currentFile / fileProgressMax * 100, 0));

    try
    {
        // Map server path for temporary file placement (Generate new serialized path for each instance)
        var tempGenFolderName = SubstringExtensions.GenerateRandomString(10, false);
        var tempPath = Server.MapPath("~/" + tempGenFolderName + "/");

        // Create Temporary Serialized Sub-Directory
        System.IO.FileInfo thisFilePath = new System.IO.FileInfo(tempPath + tempGenFolderName);
        thisFilePath.Directory.Create();

        // Iterate through PostedFileBase collection
        foreach (HttpPostedFileBase file in filesUpload)
        {

            // Does this iteration of file have content?
            if (file.ContentLength > 0)
            {
                // Indicate file is being uploaded
                hubContext.Clients.All.sendMessage("Uploading " + Path.GetFileName(file.FileName), fileProgress);

                file.SaveAs(thisFilePath + file.FileName);
                currentFile++;
            }
        }

        // Initialize new ClosedXML/Excel workbook
        var hl7Workbook = new XLWorkbook();

        // Start current file count at 1
        currentFile = 1;

        // Iterate through the files saved in the Temporary File Path
        foreach (var file in Directory.EnumerateFiles(tempPath))
        {
            var fileNameTmp = Path.GetFileName(file);

            // Update status
            hubContext.Clients.All.sendMessage("Parsing " + Path.GetFileName(file), fileProgress);

            // Initialize string to capture text from file
            string fileDataString = string.Empty;

            // Use new Streamreader instance to read text
            using (StreamReader sr = new StreamReader(file))
            {
                fileDataString = sr.ReadToEnd();
            }

            // Do more work with the file, adding file contents to a spreadsheet...


            currentFile++;
        }


        // Delete temporary file 
        thisFilePath.Directory.Delete();


        // Prepare Http response for downloading the Excel workbook
        Response.Clear();
        Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
        Response.AddHeader("content-disposition", "attachment;filename=\"hl7Parse_" + DateTime.Now.ToString("MM-dd-yyyy") + ".xlsx\"");

        // Flush the workbook to the Response.OutputStream
        using (MemoryStream memoryStream = new MemoryStream())
        {
            hl7Workbook.SaveAs(memoryStream);
            memoryStream.WriteTo(Response.OutputStream);
            memoryStream.Close();
        }

        Response.End();
    }
    catch (Exception ex)
    {
        ViewBag.TaskMessage =
            "<div style=\"margin-left:15px;margin-right:15px\" class=\"alert alert-danger\">"
            + "<i class=\"fa fa-exclamation-circle\"></i> "
            + "An error occurred during the process...<br />"
            + "-" + ex.Message.ToString()
            + "</div>"
            ;
    }

    return View();
}

在我看来(已更新以反映 Detail 的回答)...

@using (Html.BeginForm("ParseToExcel", "Task", FormMethod.Post, new { enctype = "multipart/form-data", id = "parseFrm" }))
{

    <!-- File Upload Row -->
    <div class="row">

        <!-- Select Files -->
        <div class="col-lg-6">
            <input type="file" multiple="multiple" accept=".adt" name="filesUpload" id="filesUpload" />
        </div>


        <!-- Upload/Begin Parse -->
        <div class="col-lg-6 text-right">
            <button id="beginParse" class="btn btn-success"><i class="fa fa-download"></i>&nbsp;Parse and Download Spreadsheet</button>
        </div>

    </div>

}



 <!-- Task Progress Row -->
<div class="row">

    <!-- Space Column -->
    <div class="col-lg-12">
        &nbsp;
    </div>

    <!-- Progress Indicator Column -->
    <script type="text/javascript" language="javascript">

        $(document).ready(function () {
            $('.progress').hide();

            $('#beginParse').on('click', function () {
                $('#parseFrm').submit();
            })

            $('#parseFrm').on('submit', function (e) {

                e.preventDefault();

                $.ajax({
                    url: '/Task/ParseToExcel',
                    type: "POST",
                    //success: function () {
                    //    console.log("done");
                    //}
                });

                // initialize the connection to the server
                var progressNotifier = $.connection.progressHub;

                // client-side sendMessage function that will be called from the server-side
                progressNotifier.client.sendMessage = function (message, count) {
                    // update progress
                    UpdateProgress(message, count);
                };

                // establish the connection to the server and start server-side operation
                $.connection.hub.start().done(function () {
                    // call the method CallLongOperation defined in the Hub
                    progressNotifier.server.callLongOperation();
                });
            });
        });

        function UpdateProgress(message, count) {

            // get status div
            var status = $("#status");

            // set message
            status.html(message);

            // get progress bar
            if (count > 0) {
                $('.progress').show();
            }

            $('.progress-bar').css('width', count + '%').attr('aria-valuenow', count);
            $('.progress-bar').html(count + '%');

        }


    </script>

    <div class="col-lg-12">
        <div id="status">Ready</div>
    </div>

    <div class="col-lg-12">
        <div class="progress">
            <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="min-width:20px;">
                0%
            </div>
        </div>
    </div>
</div>
<!-- Task Message Row -->
<div class="row">
    <div clss="col-lg-12">
        @Html.Raw(ViewBag.TaskMessage)
    </div>
</div>

更新:我的问题的解决方案最终成为 Detail 的答案,但是 AJAX post 方法略有修改以将文件传递给我的操作方法..

e.preventDefault();

$.ajax({
    url: '/Task/ParseToExcel',
    type: "POST",
    data: new FormData( this ),
    processData: false,
    contentType: false,
    //success: function () {
    //    console.log("done");
    //}
});

参考.. http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/

不清楚您的问题到底是什么,但是使用您的代码,我做了一些更改后就可以正常工作了。

首先,表单 post 正在重新加载页面,如果您要为此使用 POST,那么您需要通过捕获 post 事件来异步执行此操作,并且阻止默认操作(然后使用 jQuery 接管)。我不确定你打算如何触发 post(也许我只是在你的代码中错过了它),所以我添加了一个按钮并连接到它,但根据需要改变它:

<!-- Progress Indicator Column -->
<script type="text/javascript" language="javascript">

    $(document).ready(function () {
        $('.progress').hide();
        $('#button1').on('click', function () {
            $('#form1').submit();
        })

        $('#form1').on('submit', function (e) {

            e.preventDefault();

            $.ajax({
                url: '/Progress/DoTest',
                type: "POST",
                success: function () {
                    console.log("done");
                }
            });

            // initialize the connection to the server
            var progressNotifier = $.connection.progressHub;

            // client-side sendMessage function that will be called from the server-side
            progressNotifier.client.sendMessage = function (message, count) {
                // update progress
                UpdateProgress(message, count);
            };

            // establish the connection to the server and start server-side operation
            $.connection.hub.start().done(function () {
                // call the method CallLongOperation defined in the Hub
                progressNotifier.server.callLongOperation();
            });
        });
    });

    function UpdateProgress(message, count) {

        // get status div
        var status = $("#status");

        // set message
        status.html(message);

        // get progress bar
        if (count > 0)
        {
            $('.progress').show();
        }

        $('.progress-bar').css('width', count + '%').attr('aria-valuenow', count);
        $('.progress-bar').html(count + '%');

    }

</script>

<div class="col-lg-12">
    <div id="status">Ready</div>
</div>


<form id="form1">
    <button type="button" id="button1">Submit Form</button>
</form>

<div class="col-lg-12">
    <div class="progress">
        <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="min-width:20px;">
            0%
        </div>
    </div>
</div>

我还稍微简化了 Controller,以专注于手头的问题。分解问题并首先让机制工作,尤其是当您遇到问题时,然后再添加额外的逻辑:

public class ProgressController : Controller
{
    // GET: Progress
    public ActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public ActionResult DoTest()
    {
        // Initialize Hub context
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();
        hubContext.Clients.All.sendMessage("Initalizing...", 0);

        int i = 0;
        do
        {
            hubContext.Clients.All.sendMessage("Uploading ", i * 10);
            Thread.Sleep(1000);
            i++;
        }
        while (i < 10);             

        return View("Index");
    }
}

此外,请确保您的 javascript 引用顺序正确,jquery 必须首先加载,然后是信号器,然后是集线器脚本。

如果您仍有问题,post 您的确切错误消息,但我怀疑您的问题是同步 form/reload 问题。

希望对您有所帮助

好的,我玩过这个,我认为你最好使用一个名为 'jQuery Form Plugin' (http://jquery.malsup.com/form) 的插件,这将有助于解决 HttpPostedFiles 问题.

我已经采用了您的代码并进行了一些调整并使其正常运行。您需要在循环的每一轮(两个循环)期间重新计算您的文件进度,并且使用您添加到表单中的按钮不再需要通过 jQuery 触发 post 所以我评论出来了。

此外,我认为 CallLongOperation() 函数现在是多余的(我猜这只是来自源 material 的演示),所以我从您的集线器启动逻辑中删除了该调用并替换了它带有一条显示按钮的行 - 在 signalR 准备就绪之前,您可能应该阻止用户开始上传,但 signalR 几乎立即启动,所以我认为您甚至不会注意到延迟。

我不得不注释掉一些代码,因为我没有这些对象(XLWorkbook 东西、openxml 位等),但您应该能够 运行 没有这些位和跟踪通过代码遵循逻辑,然后自己添加这些位。

这是一个有趣的问题,希望我能帮到您 :)

控制器:

public class TaskController : Controller
{
    [HttpPost]
    public ActionResult ParseToExcel(HttpPostedFileBase[] filesUpload)
    {
        decimal currentFile = 1.0M;
        int fileProgress = 0;
        int maxCount = filesUpload.Count();

        // Initialize Hub context
        var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();
        hubContext.Clients.All.sendMessage("Initalizing...", fileProgress);            

        try
        {
            // Map server path for temporary file placement (Generate new serialized path for each instance)
            var tempGenFolderName = DateTime.Now.ToString("yyyyMMdd_HHmmss"); //SubstringExtensions.GenerateRandomString(10, false);
            var tempPath = Server.MapPath("~/" + tempGenFolderName + "/");

            // Create Temporary Serialized Sub-Directory
            FileInfo thisFilePath = new FileInfo(tempPath);
            thisFilePath.Directory.Create();

            // Iterate through PostedFileBase collection
            foreach (HttpPostedFileBase file in filesUpload)
            {
                // Does this iteration of file have content?
                if (file.ContentLength > 0)
                {
                    fileProgress = Convert.ToInt32(Math.Round(currentFile / maxCount * 100, 0));

                    // Indicate file is being uploaded
                    hubContext.Clients.All.sendMessage("Uploading " + Path.GetFileName(file.FileName), fileProgress);

                    file.SaveAs(Path.Combine(thisFilePath.FullName, file.FileName));
                    currentFile++;
                }
            }

            // Initialize new ClosedXML/Excel workbook
            //var hl7Workbook = new XLWorkbook();

            // Restart progress
            currentFile = 1.0M;
            maxCount = Directory.GetFiles(tempPath).Count();

            // Iterate through the files saved in the Temporary File Path
            foreach (var file in Directory.EnumerateFiles(tempPath))
            {
                var fileNameTmp = Path.GetFileName(file);

                fileProgress = Convert.ToInt32(Math.Round(currentFile / maxCount * 100, 0));

                // Update status
                hubContext.Clients.All.sendMessage("Parsing " + Path.GetFileName(file), fileProgress);

                // Initialize string to capture text from file
                string fileDataString = string.Empty;

                // Use new Streamreader instance to read text
                using (StreamReader sr = new StreamReader(file))
                {
                    fileDataString = sr.ReadToEnd();
                }

                // Do more work with the file, adding file contents to a spreadsheet...
                currentFile++;
            }


            // Delete temporary file 
            thisFilePath.Directory.Delete();


            // Prepare Http response for downloading the Excel workbook
            //Response.Clear();
            //Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
            //Response.AddHeader("content-disposition", "attachment;filename=\"hl7Parse_" + DateTime.Now.ToString("MM-dd-yyyy") + ".xlsx\"");

            // Flush the workbook to the Response.OutputStream
            //using (MemoryStream memoryStream = new MemoryStream())
            //{
            //    hl7Workbook.SaveAs(memoryStream);
            //    memoryStream.WriteTo(Response.OutputStream);
            //    memoryStream.Close();
            //}

            //Response.End();
        }
        catch (Exception ex)
        {
            ViewBag.TaskMessage =
                "<div style=\"margin-left:15px;margin-right:15px\" class=\"alert alert-danger\">"
                + "<i class=\"fa fa-exclamation-circle\"></i> "
                + "An error occurred during the process...<br />"
                + "-" + ex.Message.ToString()
                + "</div>"
                ;
        }

        return View();
    }
}

查看:

@using (Html.BeginForm("ParseToExcel", "Task", FormMethod.Post, new { enctype = "multipart/form-data", id = "parseFrm" }))
{
    <!-- File Upload Row -->
    <div class="row">

        <!-- Select Files -->
        <div class="col-lg-6">
            <input type="file" multiple="multiple" accept=".adt" name="filesUpload" id="filesUpload" />
        </div>

        <!-- Upload/Begin Parse -->
        <div class="col-lg-6 text-right">
            <button id="beginParse" class="btn btn-success"><i class="fa fa-download"></i>&nbsp;Parse and Download Spreadsheet</button>
        </div>
    </div>
}

<!-- Task Progress Row -->
<div class="row">

    <!-- Progress Indicator Column -->
    <script type="text/javascript" language="javascript">

        $(document).ready(function () {

            $('.progress').hide();
            $('#beginParse').hide();

            // initialize the connection to the server
            var progressNotifier = $.connection.progressHub;

            // client-side sendMessage function that will be called from the server-side
            progressNotifier.client.sendMessage = function (message, count) {
                // update progress
                UpdateProgress(message, count);
            };

            // establish the connection to the server
            $.connection.hub.start().done(function () {
                //once we're connected, enable the upload button
                $('#beginParse').show();
            });

            //no need for this, the button submits the form
            //$('#beginParse').on('click', function () {
            //    $('#parseFrm').submit();
            //})

            //ajaxify the form post
            $('#parseFrm').on('submit', function (e) {
                e.preventDefault();
                $('#parseFrm').ajaxSubmit();
            });
        });

        function UpdateProgress(message, count) {

            // get status div
            var status = $("#status");

            // set message
            status.html(message);

            // get progress bar
            if (count > 0) {
                $('.progress').show();
            }

            $('.progress-bar').css('width', count + '%').attr('aria-valuenow', count);
            $('.progress-bar').html(count + '%');

        }


    </script>

    <div class="col-lg-12">
        <div id="status">Ready</div>
    </div>

    <div class="col-lg-12">
        <div class="progress">
            <div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="min-width:20px;">
                0%
            </div>
        </div>
    </div>
</div>
<!-- Task Message Row -->
<div class="row">
    <div clss="col-lg-12">
        @Html.Raw(ViewBag.TaskMessage)
    </div>
</div>

p.s。不要忘记在 _Layout.cshtml:

中添加对 jQuery 表单插件的脚本引用
<script src="http://malsup.github.com/jquery.form.js"></script>