使用HttpSelfHostServer时“URI已存在注册”

时间:2014-01-29 15:44:44

标签: asp.net-web-api

我们遇到问题单元测试失败,因为以前的测试没有关闭HttpSelfHostServer的会话。

因此,当我们第二次尝试打开与服务器的连接时,我们收到此消息:

System.InvalidOperationException : A registration already exists for URI 'http://localhost:1337/'. 

此测试强制解决问题(例如):

 [TestFixture]
    public class DuplicatHostIssue 
    {
    public HttpSelfHostServer _server;

    [Test]
    public void please_work()
    {
        var config = new HttpSelfHostConfiguration("http://localhost:1337/");
        _server = new HttpSelfHostServer(config);
        _server.OpenAsync().Wait();

        config = new HttpSelfHostConfiguration("http://localhost:1337/");
        _server = new HttpSelfHostServer(config);
        _server.OpenAsync().Wait();
    }
}

所以新建服务器剂量的新实例似乎会杀死前一个会话。知道如何强制废除前一次会议吗?

完全例外,如果有帮助吗?

      System.AggregateException : One or more errors occurred.   ----> System.InvalidOperationException : A registration already exists for URI 'http://localhost:1337/'.    
    at 

System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken) at System.Threading.Tasks.Task.Wait()    
at ANW.API.Tests.Acceptance.DuplicatHostIssue.please_work() in DuplicatHostIssue.cs: line 32
    --InvalidOperationException    
at System.Runtime.AsyncResult.End(IAsyncResult result)    
at System.ServiceModel.Channels.CommunicationObject.EndOpen(IAsyncResult result) 
at System.Web.Http.SelfHost.HttpSelfHostServer.OpenListenerComplete(IAsyncResult result)

1 个答案:

答案 0 :(得分:1)

您可能希望编写如下的Dispose方法并适当调用它以避免此问题

private static void HttpSelfHostServerDispose()
{
    if (server != null)
    {
        _server.CloseAsync().Wait();
        _server.Dispose();
        _server = null;
    }
}

这将清除URI寄存器。