调试自托管的Web Api应用程序

时间:2013-11-06 11:21:37

标签: c# asp.net debugging asp.net-web-api self-hosting

我有一个带有以下控制器的WebApi应用程序:

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

路线看起来像这样

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

当我在IIS / cassini中托管服务时,如果我按预期POST到api/content/whatever,我的控制器操作就会被命中。

然而,

我有一个测试项目,SelfHosts这个api

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

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

如果我调试单元测试并进入单元测试,result是:

  

{StatusCode:500,ReasonPhrase:'Internal Server Error',版本:1.1,内容:System.Net.Http.ObjectContent`1 [[System.Web.Http.HttpError,System.Web.Http,Version = 5.0 .0.0,Culture = neutral,PublicKeyToken = 31bf3856ad364e35]],标题:   {     Content-Type:application / json;字符集= utf-8的   }}

无益,message只是

  

发生错误

有没有办法可以调试自我托管的WebApi来找出导致此错误的原因?

设置

Server只是一个来自基类的HttpServer,它拥有我自己托管的服务器,就像这样新来的:

var httpConfig = new HttpSelfHostConfiguration(BaseAddress);

new ApiServiceConfiguration(httpConfig).Configure();

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

2 个答案:

答案 0 :(得分:2)

如果启用跟踪并添加Trace.Listeners.Add(new ConsoleTraceListener()),则会收到更详细的错误消息。但是,您的问题很可能与您尝试序列化的对象无法序列化有关。

答案 1 :(得分:2)

添加到启动

config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;

其中config属于HttpConfiguration类型。

这一行代码为我解决了同样的问题 - 现在我可以看到所有内部异常的细节。

相关问题