简体   繁体   中英

Debugging a self hosted WebApi application

I have a WebApi application with the following controllor:

public class ContentController : ApiController
{
    [HttpPost]
    public HttpResponseMessage Post(string contentType)
    {
        //do stuff
        return new HttpResponseMessage(HttpStatusCode.OK);
    }
}

The route looks like this

routes.MapHttpRoute("content", 
    "api/content/{contentType}", 
    new { controller = "Content", contentType = RouteParameter.Optional });

When I host the service in IIS / cassini, if I POST to api/content/whatever then as expected, my controller action is hit.

However,

I've got a test project, that SelfHosts this api

using (var client = new HttpClient(Server))
{
    var result = client.PostAsync(BaseAddress + "api/content/whatever"

    var message = result.Content.ReadAsStringAsync().Result;
}

If I debug the unit test, and step into it, result is:

{StatusCode: 500, ReasonPhrase: 'Internal Server Error', Version: 1.1, Content: System.Net.Http.ObjectContent`1[[System.Web.Http.HttpError, System.Web.Http, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]], Headers: { Content-Type: application/json; charset=utf-8 }}

Unhelpfully, message is literally just

An error has occurred

Is there a way I can debug my self hosted WebApi to find out what is causing this error?

Set up

Server is just an HttpServer from a base class, that holds my self hosted server, new'd up like so:

var httpConfig = new HttpSelfHostConfiguration(BaseAddress);

new ApiServiceConfiguration(httpConfig).Configure();

var server = new HttpSelfHostServer(httpConfig);
server.OpenAsync().Wait();
Server = server;

If you enable tracing and add a Trace.Listeners.Add(new ConsoleTraceListener()) then you will get more detailed error messages. However, your problem is most likely related to the fact that the object that you are trying to serialize is failing to serialize.

Added to Startup

config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

where config is of HttpConfiguration type.

This single line of code solved the same issue for me - now I can see all the inner exception's details.

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