C# 从方法外部获取到操作的路由
类似于,但我希望从控制器方法外部获取路由C# 从方法外部获取到操作的路由,c#,asp.net-mvc,asp.net-core,integration-testing,url-routing,C#,Asp.net Mvc,Asp.net Core,Integration Testing,Url Routing,类似于,但我希望从控制器方法外部获取路由 [ApiController] public class TestController : ControllerBase { public IActionResult OkTest() { return Ok(true); } } 然后是一个测试类: public class TestControllerTests { private readonly HttpClient _client;
[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
}
私有字符串GetPathHere(字符串actionName)
{
var host=Program.CreateWebHostBuilder(新字符串[]{}).Build();
host.Start();
IActionDescriptorCollectionProvider=(host.Services作为ServiceProvider).GetService();
返回provider.ActionDescriptors.Items.First(i=>(i作为ControllerActionDescriptor)?.ActionName==ActionName.AttributeRouteInfo.Template;
}
[测试方法]
公共无效OkTestShouldBeFine()
{
var path=GetPathHere(nameof(valuescocontroller.OkTest));//“api/Values”在我的例子中
}
然而,我怀疑更复杂的情况需要更多的处理。看看它是否适合您的需要一个想法是使用设计用于自动化API测试的应用程序。。。。作为一个选项,您可以拥有一个代理生成器并使用生成的代理。作为另一个选项,您可以拥有一些关于API的元数据,并从元数据中获取URL。作为另一个选择,你可以依赖一些惯例。使用招摇你应该能够满足要求。看看或