2017-05-05 3 views
0

私はExceptionsFilterAttributeを使用しているエラーを管理するためにクライアントのサービスを開発するためにWeb API 2を使用していますが、このレベルではすべての例外がキャッチされません。私はWebApiConfigでGlobalExceptionHandlerWebapi 2のグローバル例外処理が行われていません

public class GlobalExceptionHandler: ExceptionHandler 
{ 
//A basic DTO to return back to the caller with data about the error 
private class ErrorInformation 
{ 
public string Message { get; set; } 
public DateTime ErrorDate { get; set; } 
} 

public override void Handle(ExceptionHandlerContext context) 
{ 

//Return a DTO representing what happened 
context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError, 
new ErrorInformation { Message="We apologize but an unexpected error occured. Please try again later.", ErrorDate=DateTime.UtcNow })); 

//This is commented out, but could also serve the purpose if you wanted to only return some text directly, rather than JSON that the front end will bind to. 
//context.Result = new ResponseMessageResult(context.Request.CreateResponse(HttpStatusCode.InternalServerError, "We apologize but an unexpected error occured. Please try again later.")); 
} 
} 

を作成 多少の誤差がprotected void Application_AuthenticateRequest(Object sender, EventArgs e)で育っていると私はそれらを処理し、彼にエラーの詳細を与えるために私たちのクライアントにカスタムメッセージを送って、これを解決するためにしたい私は、この行を追加しました:

config.Services.Replace(typeof(IExceptionHandler), new GlobalExceptionHandler()); 

Application_AuthenticateRequestは、いくつかのエラーを上げるが、GlobalExceptionHandlerは到達しません。

この問題を解決するにはどうすればよいですか?

ありがとうございます。

答えて

1

Application_AuthenticateRequestがWeb APIパイプラインに含まれていません。したがって、このメソッドで例外がスローされた場合、例外はWeb APIパイプラインが開始される前にスローされるため、Web API例外ハンドラによってキャッチされる可能性があります。

  1. いずれかの認証メカニズムを変更し、Web APIの認証(IAuthenticationFilter)を使用する代わりのApplication_AuthenticateRequestの:

    はこれを行うには2つの方法があります。

    • このプロジェクトには、MVCなどのWeb API関連のコントローラだけがあります。
  2. かのApplication_AuthenticateRequest

+0

にスローされた例外をキャッチするGlobal.asax.csファイル内のApplication_Errorを使用し、私はIAuthenticationFilterを使用し、私のためにうまく働きました –

関連する問題