asp.net公開服務地址時,由於當前用戶權限問題,會導致服務地址未添加到urlacl池中報錯。
關於添加urlacl的細節,請參考我之前的文章:asp.net self host and urlacl(解決UnHandledException Message:拒絕訪問的問題)
獲取urlacl池中存在地址否:
string _ServerLocalUrl = "http://*:22333/";
bool isExists = false;
#region 判斷存在否
try
{
var psi = new ProcessStartInfo
{
CreateNoWindow = true,
FileName = "cmd.exe",
UseShellExecute = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
Verb = "RunAs"
};
var process = Process.Start(psi);
process.StandardInput.WriteLine("netsh http show urlacl");
process.StandardInput.WriteLine("exit");
process.StandardInput.Flush();
StreamReader reader = process.StandardOutput;
string all = reader.ReadToEnd();
isExists = all.IndexOf(_ServerLocalUrl) >= 0;
process.WaitForExit(); //等待程序執行完退出進程
process.Close();
}
catch (Exception ex)
{
_Logger.Error(ex, "獲取asp.net自宿服務urlacl發生異常。");
}
#endregion 判斷存在否
接下來如果不存在,則以管理員方式註冊不存在的urlacl:
#region 如果不存在
if (!isExists)
{
var startInfo = new ProcessStartInfo
{
WindowStyle = ProcessWindowStyle.Hidden,
FileName = "cmd.exe",
Arguments = $"/C netsh http add urlacl url={_ServerLocalUrl} user=Everyone listen=yes",
Verb = "runas"
};
try
{
_Logger.Trace($"即將以管理員方式註冊不存在的urlacl。arguments = {startInfo.Arguments}");
var process = Process.Start(startInfo);
process.WaitForExit();
process.Close();
_Logger.Trace($"完成以管理員方式註冊不存在的urlacl。");
}
catch (Exception ex)
{
_Logger.Error(ex, "以管理員方式註冊不存在的urlacl發生了異常。");
}
}
#endregion 如果不存在