C# 使用MVC操作中的信号器集线器

C# 使用MVC操作中的信号器集线器,c#,asp.net-mvc,signalr,C#,Asp.net Mvc,Signalr,接下来,我将尝试显示长操作中各个步骤的进度。基于该示例,我能够成功地模拟中心内的长时间操作,并在每个步骤中将更新报告给客户端 更进一步,我现在想用[HttpPost]属性显示在MVC操作方法中发生的实时、长时间运行的进程的状态 问题是我似乎无法从中心上下文更新客户端。我意识到我必须创建一个中心上下文来使用中心进行通信。我知道的一个区别是我必须使用hubContext.Clients.All.sendMessage()VS.hubContext.Clients.Caller.sendMessage

接下来,我将尝试显示长操作中各个步骤的进度。基于该示例,我能够成功地模拟中心内的长时间操作,并在每个步骤中将更新报告给客户端

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

问题是我似乎无法从中心上下文更新客户端。我意识到我必须创建一个中心上下文来使用中心进行通信。我知道的一个区别是我必须使用
hubContext.Clients.All.sendMessage()
VS.
hubContext.Clients.Caller.sendMessage()在示例中列出。根据我在
我应该能够使用示例中所述的
Clients.Caller
,但我仅限于在hub类中使用它。主要地,我只是想了解为什么我不能从动作方法中得到信号

我提前感谢你的帮助

我已经像这样创建了我的OWIN
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();
        }
    }
}
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();
}
@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>
e.preventDefault();

$.ajax({
    url: '/Task/ParseToExcel',
    type: "POST",
    data: new FormData( this ),
    processData: false,
    contentType: false,
    //success: function () {
    //    console.log("done");
    //}
});
我的中心是这样写的…

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();
        }
    }
}
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();
}
@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>
e.preventDefault();

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

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();
        }
    }
}
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();
}
@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>
e.preventDefault();

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

参考

目前还不清楚您到底遇到了什么问题,但使用您的代码,我已经完成了这项工作,只做了一些更改

首先,表单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>

$(文档).ready(函数(){
$('.progress').hide();
$('#button1')。在('click',函数(){
$('表格1')。提交();
})
$('#form1')。关于('submit',函数(e){
e、 预防默认值();
$.ajax({
url:“/Progress/DoTest”,
类型:“POST”,
成功:函数(){
控制台日志(“完成”);
}
});
//初始化与服务器的连接
var progressNotifier=$.connection.progressHub;
//将从服务器端调用的客户端sendMessage函数
progressNotifier.client.sendMessage=函数(消息,计数){
//更新进度
UpdateProgress(消息、计数);
};
//建立与服务器的连接并启动服务器端操作
$.connection.hub.start().done(函数(){
//调用中心中定义的方法CallLongOperation
progressNotifier.server.callLongOperation();
});
});
});
函数UpdateProgress(消息、计数){
//获取状态div
var状态=$(“#状态”);
//设置消息
html(消息);
//获取进度条
如果(计数>0)
{
$('.progress').show();
}
$('.progress bar').css('width',count+'%').attr('aria-valuenow',count);
$('.progress bar').html(计数+'%');
}
准备好的
提交表格
0%
我还简化了控制器,只是为了关注手头的问题。将问题分解,首先让机械师工作,特别是当你遇到问题时,然后添加额外的逻辑:

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");
    }
}
公共类ProgressController:控制器
{
//获得:进展
公共行动结果索引()
{
返回视图();
}
[HttpPost]
公共行动结果DoTest()
{
//初始化集线器上下文
var hubContext=GlobalHost.ConnectionManager.GetHubContext();
hubContext.Clients.All.sendMessage(“初始化…”,0);
int i=0;
做
{
hubContext.Clients.All.sendMessage(“上传”,i*10);
睡眠(1000);
i++;
}
而(i<10);
返回视图(“索引”);
}
}
另外,请确保javascript引用的顺序正确,jquery必须首先加载,然后加载signar,然后加载hub脚本

如果仍然存在问题,请发布准确的错误消息,但我怀疑是同步表单/重新加载的问题


希望这对你有所帮助好吧,我已经尝试过了,我认为你最好使用一个名为“jQuery表单插件”(jQuery Form plugin)的插件,它将有助于解决HttpPostedFiles问题

我接受了你的代码,做了一些调整,使它工作起来。在每次循环(两个循环)期间,您都需要重新计算您的fileProgress,并且通过添加到表单中的按钮,不再需要通过jQuery触发post,因此我对此进行了注释

另外,我认为CallLongOperation()函数现在是多余的(我想这只是源材料中的一个演示),所以我已经从hub启动逻辑中删除了该调用,并用一行显示按钮来替换它-在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();
    }
}
公共类任务控制器:控制器
{
[HttpPost]
公共操作结果ParseToExcel(HttpPostedFileBase[]文件上载)
{
十进制当前文件=1.0M;
int fileProgress=0;
整数最大计数=