1

我有一个 WCF 方法:

[WebInvoke(Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
UriTemplate = "exception")]
public void GenerateException()

我想根据客户端(SOAP 与 JSON)返回不同的错误,因为如果我不这样做,它们似乎看不到消息。

所以我检查内容类型并相应地选择我的类型

String ct = WebOperationContext.Current.IncomingRequest.ContentType;
FaultException fe = new FaultException(errorMessage, new FaultCode(errorCode));
WebFaultException<ErrorData> errorDataWebFault = new WebFaultException<ErrorData>   (errorData, System.Net.HttpStatusCode.InternalServerError);
if (ct.Contains("text/xml"))
            throw fe;
else//Can throw any of the WebFaultExceptions here
            throw errorDataWebFault;

如果我不检查,SOAP 消费者看不到 WebFaultExceptions 的消息,JSON 消费者看不到 FaultException 的消息。

有一个更好的方法吗?感觉应该有一些“内置”的东西。

4

0 回答 0