使用signalR hub从MVC动作

本文关键字:MVC 动作 hub signalR 使用 | 更新日期: 2023-09-27 17:54:08

在本教程中,我将尝试显示长操作中各个步骤的进度。我能够成功地基于示例在集线器中模拟长时间操作,并在每一步中将更新报告给客户端。

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

问题是我似乎无法从集线器上下文更新客户端。我意识到我必须创建一个中心上下文来使用中心进行通信。我知道的一个区别是,我必须使用hubContext.Clients.All.sendMessage();hubContext.Clients.Caller.sendMessage();在例子中列出。基于我在ASP中的发现。. NET SignalR Hubs API指南-服务器我应该能够使用示例中所述的Clients.Caller,但我仅限于在hub类中使用它。我主要是想理解为什么我不能从action方法中获得信号。

我提前感谢你的帮助。

我已经创建了我自己的Startup()类,像这样

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();
}

In My 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>

更新:我的问题的解决方案最终是细节的答案,但与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/

使用signalR hub从MVC动作

好的,我有一点玩这个,我认为你会更好地使用一个名为'jQuery表单插件' (http://jquery.malsup.com/form),这将有助于HttpPostedFiles问题。

我拿了你的代码,做了一些调整,让它工作。你需要在循环的每个回合(两个循环)中重新计算你的fileProgress,并且你已经添加到表单中的按钮不再需要通过jQuery触发post,所以我把它注释掉了。

另外,我认为CallLongOperation()函数现在是多余的(我猜这只是一个演示的东西从源材料),所以我已经从你的集线器启动逻辑中删除了调用,并用一行显示按钮取代它-直到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>

注。不要忘记在_Layout.cshtml:

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

目前还不清楚您的问题是什么,但是使用您的代码,我已经在我的一端进行了一些更改。

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

<!-- 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>

我也简化了控制器一点,只是为了专注于手头的问题。首先分解问题并让机制发挥作用,特别是当你遇到问题时,然后再添加额外的逻辑:

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必须先加载,然后是signalr,然后是hub脚本。

如果你仍然有问题,发布你确切的错误信息,但我怀疑这是同步形式/重新加载的东西,这是你的问题。

希望能有所帮助