我有一个WCF 4 Rest服务,它将由java客户端和c#mvc3客户端使用。响应内容需要以json的形式返回。
我希望能够以一致的方式将任何异常/错误返回给客户端。我读到应该使用WebFaultException,它确实可以正常工作。
但是,我不想用WebFaultExceptions污染我的应用程序逻辑项目,因为它可能被非Web项目使用。
因此,我考虑在WCF Rest服务中实现IErrorHandler以捕获任何异常,然后针对特定的异常(即ValidationException),将异常作为包含在WebFaultException中的错误返回。然而,这似乎不起作用,当调用fiddler
时,我得到以下Http 504响应[Fiddler] ReadResponse()失败:服务器未返回此请求的响应。
我已经将代码简化为简单,以显示我正在做的事情的本质。
public void ProvideFault(Exception error,
MessageVersion version,
ref Message fault)
{
var ex = new WebFaultException<Exception>(
new Exception("you can't do that"),
HttpStatusCode.Unauthorized);
var xmf = ex.CreateMessageFault();
fault = Message.CreateMessage(version,
null,
xmf,
new DataContractJsonSerializer(xmf.GetType()));
}
我做错了什么?
答案 0 :(得分:2)
以下是Carlos's blog的示例代码。它在过去帮助我。
public class ValidationAwareErrorHandler : IErrorHandler
{
IErrorHandler originalErrorHandler;
public ValidationAwareErrorHandler(IErrorHandler originalErrorHandler)
{
this.originalErrorHandler = originalErrorHandler;
}
public bool HandleError(Exception error)
{
return error is ValidationException || this.originalErrorHandler.HandleError(error);
}
public void ProvideFault(Exception error, MessageVersion version, ref Message fault)
{
ValidationException validationException = error as ValidationException;
if (validationException != null)
{
fault = Message.CreateMessage(version, null, new ValidationErrorBodyWriter(validationException));
HttpResponseMessageProperty prop = new HttpResponseMessageProperty();
prop.StatusCode = HttpStatusCode.BadRequest;
prop.Headers[HttpResponseHeader.ContentType] = "application/json; charset=utf-8";
fault.Properties.Add(HttpResponseMessageProperty.Name, prop);
fault.Properties.Add(WebBodyFormatMessageProperty.Name, new WebBodyFormatMessageProperty(WebContentFormat.Json));
}
else
{
this.originalErrorHandler.ProvideFault(error, version, ref fault);
}
}
class ValidationErrorBodyWriter : BodyWriter
{
private ValidationException validationException;
Encoding utf8Encoding = new UTF8Encoding(false);
public ValidationErrorBodyWriter(ValidationException validationException)
: base(true)
{
this.validationException = validationException;
}
protected override void OnWriteBodyContents(XmlDictionaryWriter writer)
{
writer.WriteStartElement("root");
writer.WriteAttributeString("type", "object");
writer.WriteStartElement("ErrorMessage");
writer.WriteAttributeString("type", "string");
writer.WriteString(this.validationException.ValidationResult.ErrorMessage);
writer.WriteEndElement();
writer.WriteStartElement("MemberNames");
writer.WriteAttributeString("type", "array");
foreach (var member in this.validationException.ValidationResult.MemberNames)
{
writer.WriteStartElement("item");
writer.WriteAttributeString("type", "string");
writer.WriteString(member);
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.WriteEndElement();
}
}
}