Web Api 2属性路由未在MSTest项目中加载

时间:2014-07-24 19:34:59

标签: mstest asp.net-web-api2 asp.net-web-api-routing

我正在尝试为使用属性路由的Web Api 2路由创建集成测试。我在解决方案中有2个项目,一个Web Api 2项目(本例中为自托管),其中包含一个包含以下路由的控制器和一个运行测试的MSTest项目。

控制器:

public class ProductsController : ApiController
{
    Product[] products = new Product[]  
    {  
        new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 },  
        new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M },  
        new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M }  
    };

    [Route("products")]
    [HttpGet]
    public IEnumerable<Product> GetAllProducts()
    {
        return products;
    }
}

主:

    static void Main(string[] args)
    {
        var config = new HttpSelfHostConfiguration("http://localhost:8080");

        config.MapHttpAttributeRoutes();

        using (HttpSelfHostServer server = new HttpSelfHostServer(config))
        {
            server.OpenAsync().Wait();
            Console.WriteLine("Press Enter to quit.");
            Console.ReadLine();
        }
    }

当我在调试Web Api项目时从浏览器/提琴手点击它时,上面的路径运行得很好。我已经尝试过自托管和IIS,在这种情况下都可以工作。

在我的MSTest项目中,我像这样配置自主服务器:

    [TestMethod]
    public void TestMethod1()
    {
        var config = new HttpSelfHostConfiguration("http://localhost:8080");

        config.MapHttpAttributeRoutes();
        config.EnsureInitialized();

        using (HttpSelfHostServer server = new HttpSelfHostServer(config))
        {
            server.OpenAsync().Wait();

            var client = new HttpClient();
            var response = client.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://localhost:8080/products")).Result;
            var code = response.StatusCode;

            server.CloseAsync().Wait();
        }
    }

始终找不到路线。另外config.Routes不包含我的路线。我试图实现一个自定义IAssemblyResolver,试图让MapHttpAttributeRoutes()在包含控制器的程序集中找到启用属性的路由,但没有运气。

非常感谢任何帮助!

*简化了测试示例

1 个答案:

答案 0 :(得分:0)

自我主机解决方案:

此处的问题已通过自定义IAssemblyResolver解决。请参阅:https://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/CustomAssemblyResolverSample

网络主机解决方案:

这个有点棘手。在WebApiConfig.Register()中调用config.MapHttpAttributeRoutes()必须是对配置执行的第一件事。在我们定义标准模板路由之前,我已经有过这个调用,但是它上面有两个调用。 config.EnableCors()和config.AddODataQueryFilter()。一旦我将调用移到MapHttpAttributeRoutes()上面,这两个东西就开始工作了。无需自定义IAssemblyResolver。

感谢wbennet的帮助!

相关问题