2014-07-13 26 views
2

我有一个客户,谁拥有一个Web方法是这样工作的:自定义错误处理的WebMethod返回的XmlDocument

[WebMethod] 
public XmlDocument Send(string stuff) 
{ 
    // ... 
} 

目前,有一类产生的代码是重新抛出异常,触发ASP.Net对异常的标准处理。

我们希望对其进行更改,以便webmethod仍然返回状态代码500,但是我们提供了一些text/plain诊断信息,而不是默认的ASP.Net。

什么是适当的方法来做到这一点?

我将它工作,使用Context.Response.End这样的:

[WebMethod] 
public XmlDocument Send(string stuff) 
{ 
    try 
    { 
     // ...normal processing... 

     return xmlDocument; 
    } 
    catch (RelevantException) 
    { 
     // ...irrelevant cleanup... 

     // Send error 
     Context.Response.StatusCode = 500; 
     Context.Response.Headers.Add("Content-Type", "text/plain"); 
     Context.Response.Write("...diagnostic information here..."); 
     Context.Response.End(); 
     return null; 
    } 
} 

但是,这感觉哈克,所以我希望有一个更好的答案。

回答

2

但是,这感觉哈克,所以我希望有一个更好的答案。

感觉很不好意思,因为它 hacky。

更好的答案是:返回XML,就像你说的那样,用任何你想要包含的信息。该服务返回XML,它旨在用于代码而不是人员消耗。

[WebMethod] 
public XmlDocument Send(string stuff) 
{ 
    try 
    { 
     // ...normal processing, creates xmlDocument... 

     return xmlDocument; 
    } 
    catch (RelevantException) 
    { 
     // ...irrelevant cleanup... 

     // ...error processing, creates xmlDocument... 
     Context.Response.StatusCode = 500; 
     return xmlDocument; 
    } 
}