以编程方式将HttpRequestMessage发送到没有Hosting的Web API管道

时间:2014-05-07 03:55:35

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

我想知道是否有办法手动制作HTTPRequestMessage对象并以编程方式"发送"它实际上是Web API管道而没有实际托管Web API项目吗?

2 个答案:

答案 0 :(得分:2)

以下文章中描述的内存中测试是一个如何实现这一目标的示例:

http://blogs.msdn.com/b/kiranchalla/archive/2012/05/06/in-memory-client-amp-host-and-integration-testing-of-your-web-api-service.aspx

请注意,这是一篇旧帖子,但大多数概念仍然相关。

答案 1 :(得分:2)

您可以创建 HttpServer ,然后将其传递给 HttpClient 构造函数。请参阅下面的代码段:

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


            var server = new HttpServer(configuration);

            var client = new HttpClient(server);

            Task<HttpResponseMessage> task = client.GetAsync("http://www.whatever/yourcontroller");