记录一下WPF中自寄宿asp.net服务添加urlacl的问题

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 如果不存在

posted @ 2019-10-28 17:01  三台  阅读(224)  评论(0编辑  收藏  举报