2013-01-10 15 views
7

JSON'a yanıt veren bir ASP.NET ASMX WebMethod dosyasında, her ikisi de bir istisna atar & HTTP yanıt kodunu ayarlayabilir miyim? Bir HttpException attıysam, durum kodu uygun şekilde ayarlanabilseydim, ancak hizmetin 500 hatadan başka bir şeyle yanıt veremediğini düşündüm.HTTP Yanıt Kodunu & Bir ASMX JSON Hizmetinde Özel Durum Atma Kurabilir miyim?

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

:

[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; 
    } 
} 

Bunlar hem 500.

Birçok sayesinde cevap

Aşağıdaki çalıştılar.

+0

Bununla yerde aldın olacak istisna atıyor edemez zaman? –

+0

Korkarım ki değil. – Markus

cevap

2
bu kodunuzu değiştirin

:

Temelde
[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 
    } 
} 

sen, o, sonuç her zaman aynı 500.

+0

Bu, tersine sorun yaratır. İstisna, bunu hiçbir zaman tepkiye sokmaz. İstemci durum koduna sahip, ancak hata mesajına sahip değil. – Markus

+0

Neden Response.StatusDescription (ex.ToString()) 'ın her ikisine de sahip olmak için? Sadece cevabımı güncelledim. –

+1

StatusDescription StatusCode'u yansıtmalıdır (200 için OK, 404 için bulunamadı, vb). Özel bir değer olmamalı. – Markus

İlgili konular