gpt4 book ai didi

c# - 从方法外部获取操作的路由

转载 作者:行者123 更新时间:2023-12-04 10:56:41 26 4
gpt4 key购买 nike

类似于 Get the full route to current action ,但我想从 Controller 方法之外获取路由。

  [ApiController]
public class TestController : ControllerBase {

public IActionResult OkTest() {
return Ok(true);
}
}

然后是一个测试类:
public class TestControllerTests {

private readonly HttpClient _client;

public TestControllerTests() {
_client = TestSetup.GetTestClient();
}

[Test]
public async Task OkTest() {
var path = GetPathHere(); // should return "/api/test/oktest". But what is the call?
var response = await _client.GetAsync(path);
response.EnsureSuccessStatusCode();
}
}

最佳答案

这种方法似乎提供了预期的结果。但这基本上实例化了整个应用程序以获取配置的服务:

    private string GetPathHere(string actionName)
{
var host = Program.CreateWebHostBuilder(new string[] { }).Build();
host.Start();
IActionDescriptorCollectionProvider provider = (host.Services as ServiceProvider).GetService<IActionDescriptorCollectionProvider>();
return provider.ActionDescriptors.Items.First(i => (i as ControllerActionDescriptor)?.ActionName == actionName).AttributeRouteInfo.Template;
}

[TestMethod]
public void OkTestShouldBeFine()
{
var path = GetPathHere(nameof(ValuesController.OkTest)); // "api/Values" in my case
}

但是我怀疑更复杂的情况需要更多的按摩。

关于c# - 从方法外部获取操作的路由,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59125927/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com