简体   繁体   中英

Web api return 404

I'm doing some automated integration test in visual studio on my web api controller. I've got the following code in my test:

var url = serverAddress + "/api/PostalCodes?postalCode=" + postalCodeToFind;
var client = new HttpClient();
client.DefaultRequestHeaders.Add("accept", "application/json");
HttpResponseMessage response = client.GetAsync(url).Result;
response.EnsureSuccessStatusCode();

I get the following error:

System.Net.Http.HttpRequestException: Response status code does not indicate success: 404 (Not Found).

The selfhost server used:

private const string serverAddress = "http://localhost:8080";

        [TestInitialize]
        public void Initialize()
        {
            config = new HttpSelfHostConfiguration(serverAddress);

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

            config.MaxReceivedMessageSize = 2024 * 2024;
            config.MaxBufferSize = 2024 * 2024;

            server = new HttpSelfHostServer(config);
            server.OpenAsync().Wait();
        }

The weird part is that if I have my web api controller in IIS, the same URL will work just fine and return a value. I also have the same url doing a post (without the postalCodeToFind query parameter) and it also works well...

Any clues ?

The controller is not being loaded by the test.

Do you have a custom Resolver or are you expecting the baked in resolver to pick it up?

If you're using a custom Resolver (ie inheriting from DefaultAssembliesResolver), make sure the library containing the controller is being loaded.

If you're expecting the baked in resolver to pick it up, the library containing your controller needs to be in the directory that the test is running from.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM