【问题标题】:Debugging a self hosted WebApi application调试自托管的 WebApi 应用程序
【发布时间】:2013-11-06 11:21:37
【问题描述】:

我有一个带有以下控制器的 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:'内部服务器错误',版本:1.1,内容:System.Net.Http.ObjectContent`1[[System.Web.Http.HttpError,System.Web.Http,版本=5.0 .0.0,文化=中性,PublicKeyToken=31bf3856ad364e35]],标题: { 内容类型:应用程序/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;

【问题讨论】:

  • (如何)将路由分配给您的服务器,这是否发生在ApiServiceConfiguration.Configure() 中?您是否将config.IncludeErrorDetailPolicy 设置为`IncludeErrorDetailPolicy.Always'?
  • 谢谢,这为我提供了查找问题所需的详细信息。如果您创建一个答案,我会接受它。作为参考,这是我遇到的问题! stackoverflow.com/questions/19810754/…
  • @Alex 我也有同样的问题。我想调试我的自托管 api。能否请您给我一些解决方案。

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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    添加到启动

    config.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
    

    其中config 属于HttpConfiguration 类型。

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

    【讨论】:

      猜你喜欢
      • 2013-08-03
      • 1970-01-01
      • 2016-10-14
      • 2012-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多