【问题标题】:How to force WebFaultException to return custom error?如何强制 WebFaultException 返回自定义错误?
【发布时间】:2012-11-21 19:36:45
【问题描述】:

我有工作的 WCF REST Web 服务,可以像往常一样设置状态代码和状态描述:

OutgoingWebResponseContext response = WebOperationContext.Current.OutgoingResponse;
response.StatusCode = statusCode;
response.StatusDescription = detail.Error;

但我想使用 WebFaultException。不幸的是,当我运行我的代码时,它总是返回 {"Detail":"Not Found"}:

[Serializable]
[DataContract]
public class DtoError
{
    public DtoError()
    {

    }
    public DtoError(string error)
    {
        Error = error;
    }
    [DataMember]
    public string Error { get; private set; }
}

var error = new DtoError(entityName + " is not existing");
throw new WebFaultException<DtoError>(error, HttpStatusCode.NotFound);

我可以返回我的自定义错误 json 对象吗?

【问题讨论】:

    标签: wcf rest


    【解决方案1】:

    经过调查,我发现我们使用的是 Rest Starter Kit 中的 WebServiceHost2 而不是 WebServiceHost。在该主机内部,我们必须使用 WebProtocolException。所以现在我的工作代码看起来像这样:

    throw new WebProtocolException(HttpStatusCode.NotFound, "Not Found", error, null);
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-07-26
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-16
    相关资源
    最近更新 更多