2013-01-10 11 views
7

In einem ASP.NET ASMX WebMethod, das JSON antwortet, kann ich beide eine Ausnahme auslösen & den HTTP-Antwortcode festlegen? Ich dachte, wenn ich eine HttpException warf, würde der Statuscode entsprechend eingestellt werden, aber es kann den Dienst nicht dazu bringen, mit irgendetwas außer einem Fehler von 500 zu antworten.Kann ich den HTTP-Antwortcode festlegen und eine Ausnahme für einen ASMX-JSON-Dienst auslösen?

Ich habe versucht, die folgenden:

[WebMethod] 
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] 
public void TestWebMethod() { 
    throw new HttpException((int)HttpStatusCode.BadRequest, "Error Message"); 
} 

auch:

[WebMethod] 
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] 
public void TestWebMethod() { 
    try { 
     throw new HttpException((int)HttpStatusCode.BadRequest, "Error Message"); 
    } 
    catch (HttpException ex) { 
     Context.Response.StatusCode = ex.GetHttpCode(); 
     throw ex; 
    } 
} 

Diese beiden reagieren mit 500.

Vielen Dank.

+0

Hat immer sein? –

+0

Ich fürchte nicht. – Markus

Antwort

2

Ändern Sie den Code dazu:

[WebMethod] 
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)] 
public void TestWebMethod() { 
    try { 
     throw new HttpException((int)HttpStatusCode.BadRequest, "Error Message"); 
    } 
    catch (HttpException ex) { 
     Context.Response.StatusCode = ex.GetHttpCode(); 

     // See Markus comment 
     // Context.Response.StatusDescription("Error Message"); 
     // Context.Response.StatusDescription(ex.Message); // exception message 
     // Context.Response.StatusDescription(ex.ToString()); // full exception 
    } 
} 

Grundsätzlich kann man nicht, das heißt, wenn das Auslösen einer Ausnahme das Ergebnis wird Sie mit diesem erhalten überall die gleiche 500.

+0

Dies verursacht das umgekehrte Problem. Die Ausnahme erreicht die Antwort nie. Der Client hat den Statuscode, aber nicht die Fehlermeldung. – Markus

+0

Warum nicht Response.StatusDescription (ex.ToString()) beide haben? Habe gerade meine Antwort aktualisiert. –

+1

StatusDescription sollte StatusCode spiegeln (OK für 200, Nicht gefunden für 404 usw.). Es sollte kein benutzerdefinierter Wert sein. – Markus