我使用这个自定义服务器进行单元测试,我使用 MyStarup
对其进行初始化,加载测试所需的单个中间件。
这之前曾在 net47 上运行过,但在我将项目切换到 .net-core 后就停止了。现在它给了我这个非常有用的异常(exception):
System.Net.Sockets.SocketException No connection could be made because the target machine actively refused it 127.0.0.1:30001
我使用工厂方法从 IClassFixture
创建它,并使用我也使用工厂方法创建的 HttpClient
调用它,并从同一装置获取它。
public class MyServer : IDisposable
{
private readonly IWebHost _host;
public MyServer(string url) // <-- http://localhost:30001
{
_host =
new WebHostBuilder()
.UseKestrel()
.UseUrls(url)
.UseStartup<MyStartup>()
.Build();
Task = _host.StartAsync(); // <-- tried RunAsync too, no difference
}
public Task Task { get; set; }
public void Dispose()
{
_host.Dispose();
}
}
所以我的问题是,我怎样才能让它再次工作?
我读了这个Why Kestrel doesn't listen at specified port? 但这无助于解决问题。我无法将其作为控制台运行,并且它之前可以工作。为什么切换到.net-core后就停止了?
最佳答案
我明白了。您需要使用自定义配置来指定 urls
值为 Kestrel
,否则它使用一些随机(?)或默认端口 5001
。我不想使用hosting.json
所以我用了InMemoryCollection
public MyServer(string url)
{
var configuration =
new ConfigurationBuilder()
.AddInMemoryCollection(new Dictionary<string, string>
{
["urls"] = url
})
.Build();
_host =
new WebHostBuilder()
.UseKestrel()
//.UseUrls(url) // <-- cannot use this, seems to be deprecated
//.Configure(app => { app.UsePathBase(url); }) // <-- does not work
.UseConfiguration(configuration)
.UseStartup<MyStartup>()
.Build();
Task = _host.StartAsync();
}
关于c# - Kestrel 在 xUnit 测试中没有监听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57224717/