1

我的应用程序是部署在 Windows Server 2012 R2 上的 ASP.NET MVC 网站。我正在使用内置的 Windows 库 URLMoniker - urlmon.dll 来获取文件的 MIME 类型。我将其文件路径传递给 GetMimeType 方法。我面临的问题是,当我使用 Visual Studio 调试它时,它返回该文件的 mime 类型(在我的测试用例中,对于 txt 文件,它返回“application/octet-stream”)。但是在生产服务器上部署后,应用程序池意外崩溃并且日志文件中没有日志,我花了 3 天时间才了解这个代码块(在附加日志条目的帮助下)。

    private string GetMimeType(string filePath)
    {
        log.Info("Getting mime type for " + filePath);

        byte[] buffer = new byte[256];
        using (FileStream fs = new FileStream(filePath, FileMode.Open))
        {
            if (fs.Length >= 256)
                fs.Read(buffer, 0, 256);
            else
                fs.Read(buffer, 0, (int)fs.Length);
        }
        log.Info("Done reading into byte array for " + filePath);
        try
        {
            System.UInt32 mimetype;
            FindMimeFromData(0, null, buffer, 256, null, 0, out mimetype, 0);
            System.IntPtr mimeTypePtr = new IntPtr(mimetype);
            string mime = Marshal.PtrToStringUni(mimeTypePtr);
            Marshal.FreeCoTaskMem(mimeTypePtr);
            log.Info("Got mime type for " + filePath + " " + mime);
            return mime;
        }
        catch (Exception e)
        {
            log.Error("Cannot get mime type for file " + filePath, e);
            return "unknown/unknown";
        }
    }

甚至事件查看器也没有显示应用程序池崩溃的任何原因,除了以下情况:为应用程序池“SampleApp”提供服务的进程与 Windows 进程激活服务发生了致命的通信错误。进程 ID 为“yyyy”。

在尽我所能进行详细研究之后,我有以下文章可能会提供一些解决方案,但我仍然找不到这个问题的确切原因。

  1. https://www.experts-exchange.com/questions/24821266/Marshal-FreeCoTaskMem-crashing-application-in-x64-but-not-x86.html

  2. 这里的这个也面临类似的问题:https ://superuser.com/questions/568806/iis-worker-process-crashing-without-stack-trace-what-else-can-i-try

  3. 它说 urlmon.dll 可能未在系统上注册,但我已检查 Windows 注册表并已注册。事实上,该库是最新的,我需要在生产服务器上应用任何注册表更改之前找到根本原因。用新版本替换dll,修复注册表问题是我最后的手段。https://answers.microsoft.com/en-us/ie/forum/ie8-windows_7/urlmondll-causing-many-programs-to-crash/cda9a6cb-cf51-499c-8855-45c97110eafe

  4. https://social.technet.microsoft.com/Forums/windows/en-US/c3f1517b-a8c5-422e-9317-2f539715badc/ie11-x64-on-win7-crash-ntdll-urlmondll?forum=w7itprohardware

4

1 回答 1

2

您的问题是“FindMimeFromData”方法的声明!它在某些地方工作正常,并导致 iis 进程在其他地方崩溃。看看:https ://stackoverflow.com/a/18554243/4257500 您需要将“FindMimeFromData”的声明更改为:

[DllImport("urlmon.dll", CharSet = CharSet.Unicode, ExactSpelling = true, SetLastError = false)]static extern int FindMimeFromData(IntPtr pBC,
[MarshalAs(UnmanagedType.LPWStr)] string pwzUrl,
[MarshalAs(UnmanagedType.LPArray, ArraySubType=UnmanagedType.I1, SizeParamIndex=3)] 
byte[] pBuffer,
int cbSize,
[MarshalAs(UnmanagedType.LPWStr)] string pwzMimeProposed,
int dwMimeFlags,
out IntPtr ppwzMimeOut,
int dwReserved);

而且你应该做一些改变来调用这个函数。例如:

 IntPtr mimeTypePtr;
 FindMimeFromData(IntPtr.Zero, null,file, 256, null, 0,out mimeTypePtr, 0);
 var mime = Marshal.PtrToStringUni(mimeTypePtr);
于 2017-08-17T05:06:39.617 回答