参见英文答案 >
HttpListener Access Denied10个
赢7和VS2010 B2.我正在尝试使用内置的HttpListener编写一个最小的Web服务器.但是,我一直收到AccessDenied异常.这是代码:
赢7和VS2010 B2.我正在尝试使用内置的HttpListener编写一个最小的Web服务器.但是,我一直收到AccessDenied异常.这是代码:
int Run(string[] args) { _server = new HttpListener(); _server.Prefixes.Add("http://*:9669/"); _server.Start(); Console.WriteLine("Server bound to: {0}",_server.Prefixes.First()); _server.BeginGetContext(HandleContext,null); }
如果我绑定到系统端口,我可以理解需要以管理员身份运行,但我不明白为什么我对9669的绑定应该需要特殊权限.
有任何想法吗?
解决方法
感谢这个问题:
Can I listen on a port (using HttpListener or other .NET code) on Vista without requiring administrator priveleges?
我有一个答案.
netsh http add urlacl url=http://*:9669/ user=fak listen=yes
int Run(string[] args) { var prefix = "http://*:9669/"; var username = Environment.GetEnvironmentVariable("USERNAME"); var userdomain = Environment.GetEnvironmentVariable("USERDOMAIN"); _server = new HttpListener(); _server.Prefixes.Add(prefix); try { _server.Start(); } catch (HttpListenerException ex) { if (ex.ErrorCode == 5) { Console.WriteLine("You need to run the following command:"); Console.WriteLine(" netsh http add urlacl url={0} user={1}\\{2} listen=yes",prefix,userdomain,username); return -1; } else { throw; } } Console.WriteLine("Server bound to: {0}",null); }