通过自托管路由和集成测试webapi

本文关键字:集成测试 webapi 路由 | 更新日期: 2023-09-27 18:08:47

我正在使用这个代码:

[Fact]
public void ValueController_WithGetMethos_ShouldReturnValidData_NoBaseClass()
{
    var configuration = new HttpSelfHostConfiguration("http://localhost:64466");
    configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
    configuration.Services.Replace(typeof(IAssembliesResolver), new WebApiClassBase.TestAssemblyResolver(typeof(ValuesController)));
            configuration.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    var server = new HttpSelfHostServer(configuration);
    try
    {
    server.OpenAsync().Wait();
    var request = new HttpRequestMessage
    {
        RequestUri = new Uri("http://localhost:64466/api/values"),
        Method = HttpMethod.Get
    };
    var client = new HttpClient(server);
    using (HttpResponseMessage response = client.SendAsync(request).Result)
    {
        response.Should().Not.Be.Null();
        response.IsSuccessStatusCode.Should().Be.True();
        string[] result = response.Content.ReadAsAsync<string[]>().Result;
        result.Length.Should().Be.EqualTo(4);
        result[0].Should().Be.EqualTo("http://tostring.it");
        result[1].Should().Be.EqualTo("http://imperugo.tostring.it");
        result[2].Should().Be.EqualTo("http://twitter.com/imperugo");
        result[3].Should().Be.EqualTo("http://www.linkedin.com/in/imperugo");
    }
    }
    finally
    {
    configuration.Dispose();
    server.Dispose();
    }
}

受this启发,它也包含了相关的ValuesController。我注意到我必须调整路由:

configuration.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

根据我的WebApiConfig中的一个。但是,当我尝试访问带有属性路由的Action时,如下所示:

Route("Calculator/AddTwoNumbers/a/{a}/b/{a}")]
public IHttpActionResult AddTwoNumbers(PayLoad payLoad)

我得到一个404 -未找到错误。我还必须定义这种声明性路由吗?如果是这样的话,集成测试似乎相当乏味。任何反馈将非常感激。谢谢。

PS:

我试着:

configuration.MapHttpAttributeRoutes();

似乎没有帮助

通过自托管路由和集成测试webapi

您需要在配置默认路由之前设置AttributeRouting

configuration.MapHttpAttributeRoutes();
configuration.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

按照添加到RouteCollection的顺序对路由进行评估。如果你的默认路由先出现,那么它会在你的属性路由有机会被匹配之前匹配传入路由。