2016-05-11 6 views
1

Möchten Sie den Variablenwert der Aktion in kundenspezifische FilterGet Aktion lokale Variablen Namen und den Wert OnException maßgeschneiderte Filter

public class TrackError : IExceptionFilter 
      { 
       public void OnException(ExceptionContext filterContext) 
       { 
        // How to get the value of X ?????????????????     
       } 
     } 

-Controller abzurufen:

[TrackError] 
public class HomeController : Controller 
    { 

     public ActionResult Index() 
     { 

       int x = 0; 

      throw new Exception("XYZ"); 
      return View(); 
     } 
    } 

Antwort

0

Erstellen von benutzerdefinierten Ausnahme und setzen, was zusätzliche Daten, die Sie brauchen in seine Eigenschaften. Dann fangen Sie diesen Ausnahmetyp in einem Ihrer Catch-Blöcke innerhalb Ihres Ausnahmefilters ab.

public class ServiceException : Exception, ISerializable 
{ 
     public WhateverType X {get;set;} 
     public string Message{get;set;} 

     public ServiceException() 
     { 
      // Add implementation. 
     } 

     public ServiceException(WhateverType x, string message) 
     { 
      this.X = x; 
      this.Message = message; 
     } 

     public ServiceException(string message):base(message) 
     { 
     } 

     public ServiceException(string message, Exception inner) 
     { 
      // Add implementation. 
     } 

     // This constructor is needed for serialization. 
     protected ServiceException(SerializationInfo info, StreamingContext context) 
     { 
      // Add implementation. 
     } 
} 

und dann in Filter:

public override void OnException(HttpActionExecutedContext context) 
     { 
      if (context.Exception is ServiceException) 
      { 
      //Here you can access (context.Exception as ServiceException).X 
      } 
} 

Ihre Ausnahme werfen wie:

throw new ServiceException(X, "Your custom message gore here"); 
+0

noch ich nicht in der Lage bin, den Variablenwert in Filter erhalten ----- context.Exception .X gibt mir einen Fehler, dass System.Exception enthält keine Definition für X – Avin

+0

müssen Sie Ihre Ausnahme zu (context.Exception als ServiceException) .X –

+0

Dank bro Arbeit – Avin

Verwandte Themen