简体   繁体   English

ASP .NET Web API:跟踪侦听器:HTTP / 1.1 500内部服务器错误:怎么了?

[英]ASP .NET Web API: Trace Listeners: HTTP/1.1 500 Internal Server Error: What's wrong?

I've been working with .NET for a little while now, but this is my first Web API 2 project. 我已经使用.NET了一段时间,但这是我的第一个Web API 2项目。 It has been a difficult struggle, so please go easy on me. 这是一场艰苦的斗争,所以请放轻松。 There are may things about Web API that the articles out there assume to be either already known, obvious or apparent, but but are not really until you try and find out, for example, that that the "{id}" parameter is "magic" and should be used whenever possible. 关于Web API的某些事情可能认为那里的文章已经是已知的,显而易见的或显而易见的,但是直到您尝试找出例如“ {id}”参数为“ magic”后才真正知道。 ”,并应尽可能使用。

Bearing that in mind, to help to troubleshoot our application further, I attempted to enable logging using Trace Listeners and NLog, using several excellent articles as guides, including the two that follow: 牢记这一点,为了帮助进一步排除应用程序故障,我尝试使用Trace Listeners和NLog启用日志记录,并使用了几篇出色的文章作为指南,其中包括以下两篇文章:

I am trying to get an ASP .NET Web API service to run using Trace Listeners and NLog to help us to log and timestamp critical points within the application where performance is slow. 我正在尝试使用跟踪侦听器和NLog来运行ASP .NET Web API服务,以帮助我们记录性能较慢的应用程序中的关键点并为其添加时间戳。

However, when I test my controller from Fiddler, I get an exception that looks as follows: 但是,当我从Fiddler测试控制器时,出现如下异常:

 HTTP/1.1 500 Internal Server Error Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Server: Microsoft-IIS/10.0 X-AspNet-Version: 4.0.30319 X-Powered-By: ASP.NET Date: Fri, 04 Aug 2017 18:45:11 GMT Content-Length: 3617 {"Message":"An error has occurred.", "ExceptionMessage":"Value cannot be null.\\r\\nParameter name: traceWriter","ExceptionType":"System.ArgumentNullException","StackTrace":" at System.Web.Http.Tracing.ITraceWriterExtensions.Trace(ITraceWriter traceWriter, HttpRequestMessage request, String category, TraceLevel level, String messageFormat, Object[] messageArguments)\\r\\n at PURL_WebMarketing_API.Controllers.VisitorFormController.<GetFormInfo>d__3.MoveNext()\\r\\n--- End of stack trace from previous location where exception was thrown ---" } 

I'm using Visual Studio 2015, .NET Framework 4.5, and the latest NuGet packages for NLog, ASP .NET Web API, and ASP .NET Web API Tracing. 我正在使用Visual Studio 2015,.NET Framework 4.5和用于NLog,ASP.NET Web API和ASP.NET Web API跟踪的最新NuGet软件包。

Now for the code... 现在查看代码...

From App_Start/WebApiConfig.cs: 从App_Start / WebApiConfig.cs:

// Enable tracing
config.EnableSystemDiagnosticsTracing();

// Replace the default trace writer with my own custom handler
config.Services.Replace(typeof(System.Web.Http.Tracing.ITraceWriter), new Utilities.TraceHandler());

In VisitorFormController.cs: 在VisitorFormController.cs中:

public class VisitorFormController : ApiController
{
    private IDataAccessRepository _repository;
    private readonly ITraceWriter _tracer;


    public VisitorFormController(IDataAccessRepository repository): base()
    {
        _repository = repository;

        if (Request != null)
        {
            _tracer = Request.GetConfiguration().Services.GetTraceWriter();
        }
    }

[HttpGet]
        [Route("api/VisitorForm/{code}/{pageType}")]
        [EnableCors(origins: "*", headers: "*", methods: "options,get")]
        public async Task<IHttpActionResult> GetFormInfo(string code, string pageType)
        {
            DateTime startTime = DateTime.Now;

            if (string.IsNullOrEmpty(code))
                return BadRequest("Invitation code is required.");

            if (!IsValidPageType(pageType))
                return BadRequest("Valid page types may be 'post', 'info', 'No Code' or blank.");

            if (Request != null)
            {
                string startLogMessage = CustomLogMessageBuilder.GetLogMessage(CustomLogMessageBuilder.StandardStartEventNames.EVENT_TYPE_VISITOR_FORM_REQ_START);
                _tracer.Info(Request, this.ControllerContext.ControllerDescriptor.ControllerType.FullName, startLogMessage);
            }

            // *** Work happens here
            RecipientModel visitorFormInformation =  _repository.GetVisitorFormInformation(code, pageType);
            // ***

            if (visitorFormInformation == null)
                return NotFound();

            if (Request != null)
            {
                string endLogMessage = CustomLogMessageBuilder.GetLogMessage(CustomLogMessageBuilder.StandardEndEventNames.EVENT_TYPE_VISITOR_FORM_REQ_END, startTime);
                _tracer.Info(Request, this.ControllerContext.ControllerDescriptor.ControllerType.FullName, endLogMessage);
            }

            try
            {
                DateTime startLogActivityTime = DateTime.Now;

                if (Request != null)
                {
                    string startLogMessage = CustomLogMessageBuilder.GetLogMessage(CustomLogMessageBuilder.StandardStartEventNames.EVENT_TYPE_UPDATE_VISIT_LOG_FORM_VIEWED_START);
                    _tracer.Info(Request, this.ControllerContext.ControllerDescriptor.ControllerType.FullName, startLogMessage);
                }

                // Log visitor activity, asynchronously
                await _repository.LogActivity(visitorFormInformation.RecipientId, visitorFormInformation.IsCompleted);

                if (Request != null)
                {
                    string endLogMessage = CustomLogMessageBuilder.GetLogMessage(CustomLogMessageBuilder.StandardEndEventNames.EVENT_TYPE_UPDATE_VISIT_LOG_FORM_VIEWED_END, startLogActivityTime);
                    _tracer.Info(Request, this.ControllerContext.ControllerDescriptor.ControllerType.FullName, endLogMessage);
                }
            }
            catch
            {
                return BadRequest("Recipient ID#" + visitorFormInformation.RecipientId.ToString() + " not found.");
            }

            return Ok(visitorFormInformation);
        }

To see my custom trace handler, please see Filip Wojcieszyn's blog article posted above. 要查看我的自定义跟踪处理程序,请参阅上面发布的Filip Wojcieszyn的博客文章。 My version is nearly identical, so I've omitted it for brevity. 我的版本几乎相同,因此为简洁起见,我将其省略。

If I'm doing everything by the book regarding the use of trace listeners, could it be something that I'm passing in? 如果我正在做有关跟踪侦听器使用的所有工作,这可能是我要传递的东西吗? In its current state, the service works as long as the Trace Listeners are disabled. 在当前状态下,只要禁用了跟踪侦听器,该服务就可以工作。

Before anyone asks, I've tried this in various browsers. 在有人问之前,我已经在各种浏览器中进行了尝试。 But I'm at wit's help and would be most grateful for any helpful comments and suggestions. 但我能提供帮助,对于任何有用的评论和建议,我将不胜感激。 Thanks! 谢谢!

The problem is the HttpContext is not yet available in the constructor of the controller, which is why the Request property is null, which causes the _tracer to be null, which causes any function call to _tracer to throw an ArgumentNullException . 问题是HttpContext的是尚未控制器,这就是为什么的构造函数可用的Request属性为空,这将导致_tracer为空,这将导致任何函数调用_tracer抛出ArgumentNullException

I suggest you read a little bit more about the WebApi pipeline, for example here . 我建议您阅读更多有关WebApi管道的信息,例如在这里 It tells you how the controller is constructed and what happens at what point when a request is inbound. 它告诉您控制器的构造方式以及入站请求在什么时候发生。

In short: the solution is to not store the _tracer at controller level, but inside the action being executed, and get a 'new' tracer on every action call. 简而言之:解决方案是不将_tracer存储在控制器级别,而是存储在正在执行的动作中,并在每个动作调用中获取一个“ new”跟踪器。

public class VisitorFormController : ApiController
{
    private IDataAccessRepository _repository;

    public VisitorFormController(IDataAccessRepository repository): base()
    {
        _repository = repository;
    }

    [HttpGet]
    [Route("api/VisitorForm/{code}/{pageType}")]
    [EnableCors(origins: "*", headers: "*", methods: "options,get")]
    public async Task<IHttpActionResult> GetFormInfo(string code, string pageType)
    {
       var tracer = Request.GetConfiguration().Services.GetTraceWriter();

       // Use tracer from here on...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Angularjs和ASP.NET Web Api在$ http.post上导致500 Internal Server Error - Angularjs and ASP.NET Web Api cause 500 Internal Server Error on $http.post 在vs 2003中打开asp.net项目时遇到问题http / 1.1 500内部服务器错误 - getting an issue http/ 1.1 500 internal server error while opening asp.net project in vs 2003 ASP.NET Core Web API 500内部服务器错误 - ASP.NET Core Web API 500 Internal Server Error asp.net Web API内部服务器错误500 - asp.net web api internal server error 500 Web Api Get方法返回HTTP / 1.1 500 Internal Server Error - Web Api Get method returns HTTP/1.1 500 Internal Server Error JSON到ASP.NET Web API的错误:(500)内部服务器错误 - JSON to ASP.NET Web API error: (500) Internal Server Error 使用Web Api Http Put时内部服务器错误500 - Internal Server Error 500 when using Web Api Http Put Web Api和WCF中的HTTP发布内部服务器错误500 - Http Post Internal Server Error 500 in Web Api & WCF ASP.NET Web API CreatedAtRoute返回500内部服务器错误 - ASP.NET Web API CreatedAtRoute return 500 Internal Server Error ASP.NET 内核 2.2 Web API ZC31C335EF37283C451B18BA0DD317DE1。 托管服务提供商说 500 - 内部服务器错误 - ASP.NET Core 2.2 Web API Angular. Hosting provider says 500 - Internal server error
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM