【问题标题】:Get route to an action from outside the method从方法外部获取到动作的路由
【发布时间】:2019-12-01 13:24:53
【问题描述】:

类似于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();
    }
}

【问题讨论】:

  • 看看是否符合你的需求stackoverflow.com/questions/34977352/…
  • 一个想法是使用旨在自动化 API 测试的应用程序......就像 SoapUI。
  • 作为一个选项,您可以拥有一个代理生成器并使用生成的代理。作为另一种选择,您可以拥有一些关于 API 的元数据,并从元数据中获取 URL。作为另一种选择,您可以依赖一些约定。
  • 使用swagger应该可以满足要求。

标签: c# asp.net-mvc asp.net-core integration-testing url-routing


【解决方案1】:

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

    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
    }

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

【讨论】:

    猜你喜欢
    • 2013-08-25
    • 1970-01-01
    • 1970-01-01
    • 2016-12-29
    • 2022-01-02
    • 2016-11-27
    • 2014-12-15
    • 2017-02-11
    • 2019-07-22
    相关资源
    最近更新 更多