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

时间:2015-08-19 11:48:16

标签: c# asp.net-web-api asp.net-web-api2

我正在使用此代码:

[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();

似乎没有帮助

1 个答案:

答案 0 :(得分:0)

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

RouteCollection

路线按照添加到{{1}}的顺序进行评估。如果您的默认路由是第一个,那么它将匹配传入路由,然后您的属性路由才有可能匹配。