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

问题描述 投票:-1回答:1

类似于Get the full route to current action,但我想从控制器方法的外部获取路由。

  [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();
    }
}
c# asp.net-mvc asp.net-core integration-testing url-routing
1个回答
0
投票

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

    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
    }

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

© www.soinside.com 2019 - 2024. All rights reserved.