从matlab部署dll的C#.net web应用程序

时间:2016-05-13 07:27:25

标签: c# asp.net .net matlab dll

我在网站上搜索了类似的问题,似乎是一个32/64位的东西。但我仍然无法通过提供的方法来解决这个问题,例如在86/64目标平台之间切换

此处使用的软件是Visual Studio 2010和Matlab 2015a。我正在一个.m文件中测试一个非常简单的Matlab代码,该文件应该在图中绘制一条正弦曲线。此程序没有输入或输出:

function [] = testPlot()
x = 0:pi/100:2*pi;
y = sin(x);
%Create a line plot of the data.

figure % opens new figure window
plot(x,y)

它使用matlab NE构建器(我猜dll应该是64位)部署到名为testPlotN的dll,计划在c#web项目中使用。我可以在c#控制台应用程序上成功测试它(无论目标平台看起来是x86还是x64)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
using testPlotN; //dll

namespace ConsoleApplication1

{
    class Program
    {
        static void Main(string[] args)
        {
            testP obj = new testP();//class from dll
            obj.testPlot();//matlab function
            Console.ReadKey();
        }
    }
}

然而,当我在c#web应用程序中测试它时,使用主文件WebForm1.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>

        hello my name is<asp:TextBox ID="TextBox1" runat="server" 
            ontextchanged="TextBox1_TextChanged"></asp:TextBox>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="OK" />
        <br />
        <br />
        <br />
        <asp:Label ID="lbloutput" runat="server"></asp:Label>
        <br />

    </div>
    </form>

</body>
</html>

点击按钮时,按钮位于文件WebForm1.aspx.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Threading.Tasks;
using MathWorks.MATLAB.NET.Arrays;
using MathWorks.MATLAB.NET.Utility;
using testPlotN;

namespace WebApplication2
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

        }

        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {

        }

        protected void Button1_Click(object sender, EventArgs e)
        {       
            testP obj = new testP();
            obj.testPlot();
        }
    }
}

当我在构建时使用默认选择任何cpu作为平台目标时,它会完美地显示页面

1

但是当我点击按钮时,错误就出现了

Server Error in '/' Application.
--------------------------------------------------------------------------------


 An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B) 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)

Source Error: 






Line 36:             testP obj = new testP();
Line 37:             obj.testPlot();
Line 38:         }

Source File: C:\Users\M\Documents\Visual Studio 2010\Projects\WebApplication2\WebApplication2\WebForm1.aspx.cs    Line: 36 

Stack Trace: 





[BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)]
   MathWorks.MATLAB.NET.Arrays.MWArray.mclmcrInitialize2(Int32 primaryMode) +0
   MathWorks.MATLAB.NET.Arrays.MWArray..cctor() +553

[TypeInitializationException: The type initializer for 'MathWorks.MATLAB.NET.Arrays.MWArray' threw an exception.]
   MathWorks.MATLAB.NET.Utility.MWMCR..cctor() +1864

[TypeInitializationException: The type initializer for 'MathWorks.MATLAB.NET.Utility.MWMCR' threw an exception.]
   testPlotN.testP..cctor() +97

[TypeInitializationException: The type initializer for 'testPlotN.testP' threw an exception.]
   testPlotN.testP..ctor() +0
   WebApplication2.WebForm1.Button1_Click(Object sender, EventArgs e) in C:\Users\M\Documents\Visual Studio 2010\Projects\WebApplication2\WebApplication2\WebForm1.aspx.cs:36
   System.Web.UI.WebControls.Button.OnClick(EventArgs e) +9659822
   System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) +108
   System.Web.UI.WebControls.Button.System.Web.UI.IPostBackEventHandler.RaisePostBackEvent(String eventArgument) +12
   System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl, String eventArgument) +15
   System.Web.UI.Page.RaisePostBackEvent(NameValueCollection postData) +35
   System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1639

当我转向x64目标平台时,第一页甚至无法显示!并立即出现错误消息

Server Error in '/' Application.
--------------------------------------------------------------------------------


 Could not load file or assembly 'WebApplication2' or one of its dependencies. An attempt was made to load a program with an incorrect format. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 

Exception Details: System.BadImageFormatException: Could not load file or assembly 'WebApplication2' or one of its dependencies. An attempt was made to load a program with an incorrect format.

Source Error: 




An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.


Assembly Load Trace: The following information can be helpful to determine why the assembly 'WebApplication2' could not be loaded.





=== Pre-bind state information ===
LOG: DisplayName = WebApplication2
 (Partial)
WRN: Partial binding information was supplied for an assembly:
WRN: Assembly Name: WebApplication2 | Domain ID: 5
WRN: A partial bind occurs when only part of the assembly display name is provided.
WRN: This might result in the binder loading an incorrect assembly.
WRN: It is recommended to provide a fully specified textual identity for the assembly,
WRN: that consists of the simple name, version, culture, and public key token.
WRN: See whitepaper http://go.microsoft.com/fwlink/?LinkId=109270 for more information and common solutions to this issue.
LOG: Appbase = file:///C:/Users/M/Documents/Visual Studio 2010/Projects/WebApplication2/WebApplication2/
LOG: Initial PrivatePath = C:\Users\M\Documents\Visual Studio 2010\Projects\WebApplication2\WebApplication2\bin
Calling assembly : (Unknown).
===
LOG: This bind starts in default load context.
LOG: Using application configuration file: C:\Users\M\Documents\Visual Studio 2010\Projects\WebApplication2\WebApplication2\web.config
LOG: Using host configuration file: 
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL file:///C:/Users/M/AppData/Local/Temp/Temporary ASP.NET Files/root/3bb260af/e3ca09a0/WebApplication2.DLL.
LOG: Attempting download of new URL file:///C:/Users/M/AppData/Local/Temp/Temporary ASP.NET Files/root/3bb260af/e3ca09a0/WebApplication2/WebApplication2.DLL.
LOG: Attempting download of new URL file:///C:/Users/M/Documents/Visual Studio 2010/Projects/WebApplication2/WebApplication2/bin/WebApplication2.DLL.
ERR: Failed to complete setup of assembly (hr = 0x8007000b). Probing terminated.


Stack Trace: 





[BadImageFormatException: Could not load file or assembly 'WebApplication2' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Reflection.RuntimeAssembly._nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +0
   System.Reflection.RuntimeAssembly.nLoad(AssemblyName fileName, String codeBase, Evidence assemblySecurity, RuntimeAssembly locationHint, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +36
   System.Reflection.RuntimeAssembly.InternalLoadAssemblyName(AssemblyName assemblyRef, Evidence assemblySecurity, RuntimeAssembly reqAssembly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean throwOnFileNotFound, Boolean forIntrospection, Boolean suppressSecurityChecks) +152
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean forIntrospection) +77
   System.Reflection.RuntimeAssembly.InternalLoad(String assemblyString, Evidence assemblySecurity, StackCrawlMark& stackMark, Boolean forIntrospection) +21
   System.Reflection.Assembly.Load(String assemblyString) +28
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +38

[ConfigurationErrorsException: Could not load file or assembly 'WebApplication2' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.Configuration.CompilationSection.LoadAssemblyHelper(String assemblyName, Boolean starDirective) +738
   System.Web.Configuration.CompilationSection.LoadAllAssembliesFromAppDomainBinDirectory() +217
   System.Web.Configuration.CompilationSection.LoadAssembly(AssemblyInfo ai) +130
   System.Web.Compilation.BuildManager.GetReferencedAssemblies(CompilationSection compConfig) +170
   System.Web.Compilation.BuildManager.GetPreStartInitMethodsFromReferencedAssemblies() +92
   System.Web.Compilation.BuildManager.CallPreStartInitMethods(String preStartInitListPath, Boolean& isRefAssemblyLoaded) +290
   System.Web.Compilation.BuildManager.ExecutePreAppStart() +157
   System.Web.Hosting.HostingEnvironment.Initialize(ApplicationManager appManager, IApplicationHost appHost, IConfigMapPathFactory configMapPathFactory, HostingEnvironmentParameters hostingParameters, PolicyLevel policyLevel, Exception appDomainCreationException) +531

[HttpException (0x80004005): Could not load file or assembly 'WebApplication2' or one of its dependencies. An attempt was made to load a program with an incorrect format.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +9920756
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +101
   System.Web.HttpRuntime.ProcessRequestInternal(HttpWorkerRequest wr) +456



--------------------------------------------------------------------------------
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.6.81.0 

我花了两天时间来调试它。但是我甚至无法通过提供的方法来解决这个问题,例如在86/64目标平台和iis设置之间切换以启用32位应用程序。

任何线索都会非常感激!

3 个答案:

答案 0 :(得分:1)

通过启用我的案例解决了问题 将64位版本的IIS Express用于网站和项目

点击工具 - &gt;选项 - &gt;项目和解决方案 - &gt;网络项目

单击复选框以启用对网站和项目使用64位版本的IIS Express

答案 1 :(得分:0)

这可能与您正在使用的.NET版本以及内置DLL的内容有关。尝试将以下内容添加到配置文件(Web.Config):

<configuration>
  <startup useLegacyV2RuntimeActivationPolicy="true">
    <supportedRuntime version="v4.0"/>
    <supportedRuntime version="v2.0.50727"/>
  </startup>
</configuration>

此外,&#34;管理的管道&#34;应该在IIS中设置为Classic

答案 2 :(得分:0)

我的MatLab到.NET代码遇到了同样的问题。以下是两件事:

  1. 在Visual Studio中,在“项目属性”下 - &gt;构建,将平台目标设置为x64。这将使其适用于在IIS Express中进行测试。

  2. 部署时,只需将“启用32位应用程序”更改为“假”,确保将应用程序池设置为64位。

  3. 当我遇到这个问题时,这对我有用。