Internal server error in ASP.NET Web API test in memory

I get an “internal server error” (status code 500) when testing an ASP.NET web API controller in an in-memory test .

[TestFixture]
public class ValuesControllerTest
{
    private HttpResponseMessage response;

    [TestFixtureSetUp]
    public void Given()
    {
        var config = new HttpConfiguration
        {
            IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always
        };

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { controller = typeof(ValuesController).Name.Replace("Controller", string.Empty), id = RouteParameter.Optional }
        );

        //This method will cause internal server error but NOT throw any exceptions
        //Remove this call and the test will be green
        ScanAssemblies();

        var server = new HttpServer(config);
        var client = new HttpClient(server);
        response = client.GetAsync("http://something/api/values/5").Result;
        //Here response has status code 500

    }

    private void ScanAssemblies()
    {
        PluginScanner.Scan(".\\", IsApiController);
    }

    private bool IsApiController(Type type)
    {
        return typeof (ApiController).IsAssignableFrom(type);
    }

    [Test]
    public void Can_GET_api_values_5()
    {
        Assert.IsTrue(response.IsSuccessStatusCode);
    }
}

public static class PluginScanner
{
    public static IEnumerable<Type> Scan(string directoryToScan, Func<Type, bool> filter)
    {
        var result = new List<Type>();
        var dir = new DirectoryInfo(directoryToScan);

        if (!dir.Exists) return result;

        foreach (var file in dir.EnumerateFiles("*.dll"))
        {
            result.AddRange(from type in Assembly.LoadFile(file.FullName).GetTypes()
                            where filter(type)
                            select type);
        }
        return result;
    }
}

I set Visual Studio to break when any .Net exception is thrown. The code does not stop under any circumstances, and I cannot find any exception details in the answer.

What to do to find out what causes the "internal server error"?

+6
source share
3 answers

An exception is in Response.Content

if (Response != null && Response.IsSuccessStatusCode == false)
{
    var result = Response.Content.ReadAsStringAsync().Result;
    Console.Out.WriteLine("Http operation unsuccessful");
    Console.Out.WriteLine(string.Format("Status: '{0}'", Response.StatusCode));
    Console.Out.WriteLine(string.Format("Reason: '{0}'", Response.ReasonPhrase));
    Console.Out.WriteLine(result);
}
+11
source

You need to add a route so that it looks something like this:

        var config = new HttpConfiguration()
        {
            IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always
        };

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

        var server = new HttpServer(config);
        var client = new HttpClient(server);

        HttpResponseMessage response = client.GetAsync("http://somedomain/api/product").Result;

Btw, in the last bits you get 404 Not Found, as you expected.

Henric

+4

, , , .

, , , MVC 4. (IncludeErrorDetailPolicy, CustomErrors ..), " " 500.

, :

public class XmlMediaTypeFormatterWrapper : XmlMediaTypeFormatter
{
    public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext transportContext)
    {
        var ret = base.WriteToStreamAsync(type, value, stream, contentHeaders, transportContext);
        if (null != ret.Exception)
            // This means there was an error and ret.Exception has all the error message data you would expect, but once you return below, all you get is a blank 500 error...

        return ret;
    } 
}

Xml Json, ret.Exception , , , , 500. html-, Task.Exception , , , .

0

All Articles