2 回答

TA貢獻2012條經驗 獲得超12個贊
正如對您問題本身的評論中所建議的那樣,在使用InProcess托管模型運行時,應用程序的當前目錄與OutOfProcess托管模型不同。對于InProcess,此目錄是 IIS 本身的位置 - 例如C:\Program Files\IIS Express,這意味著正在寫入您的日志文件C:\Program Files\IIS Express\Logs\log-.txt(假設已設置相關權限)。
此 GitHub 問題中詳細介紹了解決此問題的方法,它提供了一個幫助類 ( CurrentDirectoryHelpers) 用于設置正確的當前目錄。靜態方法使用SetCurrentDirectoryPInvoke,確定應用程序是否在 IIS 中運行,如果是,則根據完整的應用程序路徑設置當前目錄。使用這種方法看起來像這樣:
public class Program
{
public static void Main(string[] args)
{
CurrentDirectoryHelpers.SetCurrentDirectory();
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Information() // Set the minimun log level
.WriteTo.File("Logs\\log-.txt", rollingInterval: RollingInterval.Day, retainedFileCountLimit: 7) // this is for logging into file system
.CreateLogger();
...
}
}
這是CurrentDirectoryHelpers為了完整性:
using System;
namespace SampleApp
{
internal class CurrentDirectoryHelpers
{
internal const string AspNetCoreModuleDll = "aspnetcorev2_inprocess.dll";
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern IntPtr GetModuleHandle(string lpModuleName);
[System.Runtime.InteropServices.DllImport(AspNetCoreModuleDll)]
private static extern int http_get_application_properties(ref IISConfigurationData iiConfigData);
[System.Runtime.InteropServices.StructLayout(System.Runtime.InteropServices.LayoutKind.Sequential)]
private struct IISConfigurationData
{
public IntPtr pNativeApplication;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.BStr)]
public string pwzFullApplicationPath;
[System.Runtime.InteropServices.MarshalAs(System.Runtime.InteropServices.UnmanagedType.BStr)]
public string pwzVirtualApplicationPath;
public bool fWindowsAuthEnabled;
public bool fBasicAuthEnabled;
public bool fAnonymousAuthEnable;
}
public static void SetCurrentDirectory()
{
try
{
// Check if physical path was provided by ANCM
var sitePhysicalPath = Environment.GetEnvironmentVariable("ASPNETCORE_IIS_PHYSICAL_PATH");
if (string.IsNullOrEmpty(sitePhysicalPath))
{
// Skip if not running ANCM InProcess
if (GetModuleHandle(AspNetCoreModuleDll) == IntPtr.Zero)
{
return;
}
IISConfigurationData configurationData = default(IISConfigurationData);
if (http_get_application_properties(ref configurationData) != 0)
{
return;
}
sitePhysicalPath = configurationData.pwzFullApplicationPath;
}
Environment.CurrentDirectory = sitePhysicalPath;
}
catch
{
// ignore
}
}
}
}
- 2 回答
- 0 關注
- 283 瀏覽
添加回答
舉報