从ASP.NET [ScriptService]服务全局日志异常 [英] Globally log exceptions from ASP.NET [ScriptService] services

查看:369
本文介绍了从ASP.NET [ScriptService]服务全局日志异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用[System.Web.Script.Services.ScriptService]标签来使用可从客户端javascript调用的Web服务。我需要的是在这些方法中全局记录任何未处理的异常的方法。在客户端,我得到错误回调,可以从那里继续,但是我需要一个服务器端的catch来记录异常。

I'm using the [System.Web.Script.Services.ScriptService] tag to use web services callable from client side javascript. What I need is a way of globally logging any unhandled exceptions in those methods. On the client side, I get the error callback and can proceed from there, but I need a server-side catch to log the exception.

这个URL的家伙:
http ://ayende.com/Blog/archive/2008/01/06/ASP.Net-Ajax-Error-Handling-and-WTF.aspx

The guy at this url: http://ayende.com/Blog/archive/2008/01/06/ASP.Net-Ajax-Error-Handling-and-WTF.aspx

表示这是无法做到的。

是否准确?我真的不得不去整个系统中的每一个web方法,并尝试/捕获整个方法。

Is that accurate? Do I seriously have to go to every single webmethod in the entire system and try/catch the method as a whole.

推荐答案

你可以使用HTTP模块捕获Web服务方法抛出的异常消息,堆栈跟踪和异常类型。

You can use an HTTP module to capture the exception message, stack trace and exception type that is thrown by the web service method.

首先有一些背景...

First some background...


  • 如果Web服务方法抛出异常,则HTTP响应的状态代码为500。

  • If a web service method throws an exception the HTTP response has a status code of 500.

如果自定义错误关闭,那么web
服务将返回异常
消息和堆栈跟踪到客户端
作为JSON。例如:
{Message:Exception
message,StackTrace:at
WebApplication.HelloService.HelloWorld()
在C: \Projects\Stackoverflow
示例\WebApplication\WebApplication\HelloService.asmx.cs:line
22,ExceptionType:System.ApplicationException}

If custom errors are off then the web service will return the exception message and stack trace to the client as JSON. For example:
{"Message":"Exception message","StackTrace":" at WebApplication.HelloService.HelloWorld() in C:\Projects\Stackoverflow Examples\WebApplication\WebApplication\HelloService.asmx.cs:line 22","ExceptionType":"System.ApplicationException"}

当自定义错误打开时,
Web服务会向客户端返回一条默认消息
,并删除堆栈
跟踪和异常类型:
{Message:处理请求时出错,StackTrace:,ExceptionType:}

When custom errors are on then the web service returns a default message to the client and removes the stack trace and exception type:
{"Message":"There was an error processing the request.","StackTrace":"","ExceptionType":""}

所以我们需要做的是为Web服务设置自定义错误,并插入一个HTTP模块

So what we need to do is set custom errors off for the web service and plug in an HTTP module that:


  1. 检查请求是否适用于Web服务方法

  2. 检查是否引发了异常 - 也就是说,状态代码为500正在返回

  3. 如果1)和2)是真的,那么得到将发送到clie的原始JSON nt并将其替换为默认的JSON

以下代码是HTTP模块的示例:

The code below is an example of an HTTP module that does this:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Web;

public class ErrorHandlerModule : IHttpModule {

  public void Init(HttpApplication context) {
    context.PostRequestHandlerExecute += OnPostRequestHandlerExecute;
    context.EndRequest += OnEndRequest;
  }

  static void OnPostRequestHandlerExecute(object sender, EventArgs e) {
    HttpApplication context = (HttpApplication) sender;
    // TODO: Update with the correct check for your application
    if (context.Request.Path.StartsWith("/HelloService.asmx") 
        && context.Response.StatusCode == 500) {
      context.Response.Filter = 
        new ErrorHandlerFilter(context.Response.Filter);
      context.EndRequest += OnEndRequest;
    }
  }

  static void OnEndRequest(object sender, EventArgs e) {
    HttpApplication context = (HttpApplication) sender;
    ErrorHandlerFilter errorHandlerFilter = 
      context.Response.Filter as ErrorHandlerFilter;
    if (errorHandlerFilter == null) {
      return;
    }

    string originalContent =
      Encoding.UTF8.GetString(
        errorHandlerFilter.OriginalBytesWritten.ToArray());

    // If customErrors are Off then originalContent will contain JSON with
    // the original exception message, stack trace and exception type.

    // TODO: log the exception
  }

  public void Dispose() { }
}

此模块使用以下过滤器来覆盖发送到客户端的内容并存储原始字节(其中包含异常消息,堆栈跟踪和异常类型):

This module uses the following filter to override the content sent to the client and to store the original bytes (which contain the exception message, stack trace and exception type):

public class ErrorHandlerFilter : Stream {

  private readonly Stream _responseFilter;

  public List OriginalBytesWritten { get; private set; }

  private const string Content = 
    "{\"Message\":\"There was an error processing the request.\"" +
    ",\"StackTrace\":\"\",\"ExceptionType\":\"\"}";

  public ErrorHandlerFilter(Stream responseFilter) {
    _responseFilter = responseFilter;
    OriginalBytesWritten = new List();
  }

  public override void Flush() {
    byte[] bytes = Encoding.UTF8.GetBytes(Content);
    _responseFilter.Write(bytes, 0, bytes.Length);
    _responseFilter.Flush();
  }

  public override long Seek(long offset, SeekOrigin origin) {
    return _responseFilter.Seek(offset, origin);
  }

  public override void SetLength(long value) {
    _responseFilter.SetLength(value);
  }

  public override int Read(byte[] buffer, int offset, int count) {
    return _responseFilter.Read(buffer, offset, count);
  }

  public override void Write(byte[] buffer, int offset, int count) {
    for (int i = offset; i < offset + count; i++) {
      OriginalBytesWritten.Add(buffer[i]);
    }
  }

  public override bool CanRead {
    get { return _responseFilter.CanRead; }
  }

  public override bool CanSeek {
    get { return _responseFilter.CanSeek; }
  }

  public override bool CanWrite {
    get { return _responseFilter.CanWrite; }
  }

  public override long Length {
    get { return _responseFilter.Length; }
  }

  public override long Position {
    get { return _responseFilter.Position; }
    set { _responseFilter.Position = value; }
  }
}

此方法需要关闭Web服务的自定义错误。您可能希望为应用程序的其余部分保留自定义错误,以便Web服务应放在子目录中。可以在该目录中关闭自定义错误,只能使用覆盖父设置的web.config。

This method requires custom errors to be switched off for the web services. You would probably want to keep custom errors on for the rest of the application so the web services should be placed in a sub directory. Custom errors can be switched off in that directory only using a web.config that overrides the parent setting.

这篇关于从ASP.NET [ScriptService]服务全局日志异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆