Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
320 views
in Technique[技术] by (71.8m points)

c# - How does the In-Memory HttpServer know which WebAPI project to host?

I want to run tests against WebAPI project using a popular in-memory hosting strategy.

My tests reside in a separate project.

Here's the start of my test

    [TestMethod]
    public void TestMethod1()
    {
        HttpConfiguration config = new HttpConfiguration();

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

        HttpServer server = new HttpServer(config);
        HttpMessageInvoker client = new HttpMessageInvoker(server)
    }

The client is initialized with the HttpServer, establishing the direct client-server connection.

Other than providing route config info, how does HttpServer know which WebAPI project to host?

How to host multiple WebAPI projects at the same time?

Seems HttpServer does some magic to locate WebAPI projects?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Web API depends on a service called IAssembliesResolver to get all the assemblies and scans them to find controllers which implement the IHttpController interface.

Now sometimes Web API might be unable to find your controller depending on whether the assembly has been loaded into the current app domain or not. In that scenario you would need to make sure that your assembly is loaded.

Looking at your sample test code, it appears that you are not referring to any type from your Web API project in which case i assume the Web API project's assembly would not be loaded.

Also you seem to be registering the routes again in your test. I would suggest to use the WebApiConfig.Register(HttpConfiguration) of your Web API project to do all the registration stuff. This way you would be testing with the same settings that your Web API project has.

Notes:

  1. When running tests using in-memory server, your requests/responses wouldn't go through the formatters' serialization/deserialization process which is dangerous as you could be having real issues during them. So you would need to make sure to take care about this. Long time back i wrote a blog post regarding this. You can check it out here.

  2. Fiddler tool is very useful in looking at the raw requests/responses to diagnose any issues. You would be loosing this ability if you are doing in-memory testing though.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...