我在C#中编写HTTP服务器.
当我尝试执行该功能时,HttpListener.Start()我得到一个HttpListenerException说法
"拒绝访问".
当我在Windows 7中以管理模式运行应用程序时,它工作正常.
我可以在没有管理员模式的情况下运行吗 如果有,怎么样?如果不是,如何在开始运行后让应用程序更改为管理模式?
using System;
using System.Net;
namespace ConsoleApplication1
{
class Program
{
private HttpListener httpListener = null;
static void Main(string[] args)
{
Program p = new Program();
p.Server();
}
public void Server()
{
this.httpListener = new HttpListener();
if (httpListener.IsListening)
throw new InvalidOperationException("Server is currently running.");
httpListener.Prefixes.Clear();
httpListener.Prefixes.Add("http://*:4444/");
try
{
httpListener.Start(); //Throws Exception
}
catch (HttpListenerException ex)
{
if (ex.Message.Contains("Access is denied"))
{
return;
}
else
{
throw;
}
}
}
} …Run Code Online (Sandbox Code Playgroud) 我在这里的示例是关于自托管的ASP.NET Web API服务.但是,当将"localhost"指定为基址中的主机时,它将转换为"+"(表示"全部可用").
var baseAddress = new Uri("http://localhost:13210");
var configuration = new HttpSelfHostConfiguration(baseAddress);
configuration.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new {id = RouteParameter.Optional});
using (var server = new HttpSelfHostServer(configuration))
{
server.OpenAsync().Wait();
stop.WaitOne();
server.CloseAsync().Wait();
}
Run Code Online (Sandbox Code Playgroud)
我真的希望我的主机只能绑定到"localhost" - 它只能从同一台机器上访问,而且我不想乱用URL ACL.
如何配置Web API以不将"localhost"重写为"+"?