从 ASP MVC 控制器运行 Word 时继续获取 InteropServices.COMException



我收到错误远程过程调用失败 HRESULT:从我的 ASP .NET MVC 应用程序中的控制器运行 Microsoft.Interop.Word 时0x800706BE异常。奇怪的是,如果我调试应用程序并逐步运行它,则不会引发异常。我一直无法理解我在微软上找到的关于此异常的少数文档。我读到的是与 Word 在调用时关闭套接字有关,但我对此一无所知,所以我希望有人可能知道问题可能是什么。异常总是在我的代码的特定行抛出(我已经评论了它失败的地方):

//
    // GET /Asistencia/PrintDocentes
    public ActionResult PrintDocentes(int IdCurso)
    {
        List<AsistenciaDocentesViewModel> materias = new Metodos.Entidades().getListadoProfesores(IdCurso);
        List<int> compartidas = new List<int>();
        compartidas = materias.GroupBy(t => t.IdMateriasCursos).Where(t => t.Count() > 1).Select(t => t.Key).ToList();
        List<string> catedrasCompartidas = new List<string>();
        catedrasCompartidas= materias.Where(s => compartidas.Any(t=> t.Equals(s.IdMateriasCursos))).Select(r => r.NombresMaestro).ToList();
        string document = "asistenciaDocentes.docx";
        string uploadsFolder = HostingEnvironment.MapPath("~/App_Data/Docs");
        string imageFolder = HostingEnvironment.MapPath("~/Images/Docs");
        string[] encabezado = { "logoCideAsistencia.jpg", "logoSegobAsistencia.jpg", "logoPFAsistencia.jpg", "logoDiplomadoAsistencia.jpg" };
        string archivo = Path.Combine(uploadsFolder, @document);
        ApWord = new Word.Application();
        docAsistencia = ApWord.Documents.Add(ref opc, ref opc, ref opc, ref opc);
        ApWord.Visible = true;
        docAsistencia.PageSetup.RightMargin = (float)100;
        docAsistencia.PageSetup.LeftMargin = (float)60;
        foreach (Word.Section section in ApWord.ActiveDocument.Sections)
        {
            Word.Range headerRange = section.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range;
            for (int i = 0; i < encabezado.Length; i++)
            {
                headerRange.Collapse(Word.WdCollapseDirection.wdCollapseStart);
                string path = Path.Combine(imageFolder, encabezado[i]);
                Word.InlineShape map = headerRange.InlineShapes.AddPicture(path);
                if (i == 0) { map.Height = 48; map.Width = 39; } /*********
*********************This is the line that throws the exception ********/
                if (i == 1) { map.Width = 263; map.Height = 39; }
                if (i == 2) { map.Width = 141; map.Height = 26; }
                headerRange.Move(Word.WdUnits.wdCharacter);
                headerRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
                if (i == 2) break;
            }
            Word.Shape titulo = docAsistencia.Shapes.AddTextbox(Microsoft.Office.Core.MsoTextOrientation.msoTextOrientationHorizontal,60, 5, 300, 50, ref opc);
            titulo.TextFrame.TextRange.Text = "DIPLOMADO EN MANDO POLICIAL 2015nLista de Asistencia de profesoresn";
            titulo.Line.Visible = MsoTriState.msoFalse;
            titulo.TextFrame.TextRange.Font.Name = "Cambria";
            titulo.TextFrame.TextRange.Font.Size = 16;
            titulo.TextFrame.TextRange.Font.Bold = 1;
            titulo.TextFrame.TextRange.Font.Italic = 1;

            headerRange.ParagraphFormat.Alignment = Word.WdParagraphAlignment.wdAlignParagraphRight;
            Word.InlineShape map2 = headerRange.InlineShapes.AddPicture(Path.Combine(imageFolder, encabezado[3]));
            map2.Height = 106;
            map2.Width = 137;

        }
        foreach(AsistenciaDocentesViewModel item in materias)
        {
        Word.Paragraph grupo1 = docAsistencia.Paragraphs.Add(ref opc);
        grupo1.Range.Font.Name = "Arial";
        grupo1.Range.Font.Size = 14;
        grupo1.Range.Font.Bold = 1;
        grupo1.Range.InsertAfter("Semanat" + item.Semana);
        Word.Paragraph grupo2 = docAsistencia.Paragraphs.Add();
        grupo2.Range.InsertAfter("Sedet" + item.Sede);
        Word.Paragraph grupo3 = docAsistencia.Paragraphs.Add();
        grupo3.Range.InsertAfter("Grupot" + item.Grupo);
        Word.Paragraph grupo4 = docAsistencia.Paragraphs.Add();
        docAsistencia.Words.Last.InsertBreak(Word.WdBreakType.wdLineBreak);
        grupo4.Range.InsertAfter("Fechat" + item.Fecha);
        Word.Paragraph grupo5 = docAsistencia.Paragraphs.Add();
        grupo5.Range.InsertAfter("Díat" + item.Dia);
        Word.Paragraph grupo6 = docAsistencia.Paragraphs.Add();
        grupo6.Range.InsertAfter("Horariot" + item.HorarioInicio + " - " + item.HorarioFin);
        Word.Paragraph grupo7 = docAsistencia.Paragraphs.Add();
        grupo7.Range.InsertAfter("compartir");
        if (compartidas.Contains(item.IdMateriasCursos))
        {
            List<AsistenciaDocentesViewModel> compartir = materias.Where(t => t.IdMateriasCursos.Equals(item.IdMateriasCursos)).ToList();
            List<string> catedras = compartir.Select(t => t.NombresMaestro).ToList();
            List<string> catedras_aImprimir = catedras.Where(t => !t.Equals(item.NombresMaestro)).ToList();
            foreach (string catedra in catedras_aImprimir)
            {
                Word.Paragraph grupo8 = docAsistencia.Paragraphs.Add();
                grupo8.Range.InsertAfter(catedra);
            }
            docAsistencia.Words.Last.InsertBreak(Word.WdBreakType.wdLineBreak);
        }
        Word.Paragraph grupo9 = docAsistencia.Paragraphs.Add();
        grupo9.Range.InsertAfter("Módulo");
        Word.Paragraph grupo10 = docAsistencia.Paragraphs.Add(); 
        grupo10.Range.InsertAfter(item.Modulo);
        Word.Paragraph grupo11 = docAsistencia.Paragraphs.Add();
        grupo11.Range.InsertAfter("Materia");
        Word.Paragraph grupo12 = docAsistencia.Paragraphs.Add();
        grupo12.Range.InsertAfter(item.Materia);
        Word.Paragraph grupo13 = docAsistencia.Paragraphs.Add();
        grupo13.Range.InsertAfter("Profesor");
        Word.Paragraph grupo14 = docAsistencia.Paragraphs.Add();
        grupo14.Range.InsertAfter(item.NombresMaestro);
        Word.Paragraph grupo15 = docAsistencia.Paragraphs.Add();
        grupo15.Range.InsertAfter("Firma:______________________________________________________");
        docAsistencia.Words.Last.InsertBreak(Word.WdBreakType.wdPageBreak);
        }
        docAsistencia.SaveAs2(archivo, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc, ref opc,
            ref opc, ref opc, ref opc, ref opc, ref opc, ref opc);
        docAsistencia.Close();
        Marshal.FinalReleaseComObject(ApWord);
        Marshal.FinalReleaseComObject(docAsistencia);
        GC.Collect();
        GC.WaitForPendingFinalizers();
        GC.Collect();
        return RedirectToAction("VerRecursos", new { file = document });
    }

请帮忙,我以前没有使用过互操作,所以我真的猜不出出了什么问题,我想也许两个周期可能会导致问题,但我真的不知道。

Microsoft 当前不建议也不支持从任何无人参与、非交互式客户端应用程序或组件(包括 ASP、ASP.NET、DCOM 和 NT 服务)自动化Microsoft Office 应用程序,因为在此环境中运行 Office 时 Office 可能会表现出不稳定的行为和/或死锁。

如果要生成在服务器端上下文中运行的解决方案,则应尝试使用已安全执行无人参与的组件。或者,您应该尝试找到至少允许部分代码在客户端运行的替代方法。如果使用服务器端解决方案中的 Office 应用程序,则该应用程序将缺少成功运行所需的许多功能。此外,您将承担整体解决方案稳定性的风险。可以在 Office 服务器端自动化的注意事项一文中阅读有关此内容的详细信息。

请考虑使用 Open XML SDK,

有关详细信息,请参阅欢迎使用 Open XML SDK 2.5 for Office。此外,您还可以找到专为服务器端执行而设计的第三方组件。

相关内容

最新更新