Skip to main content
 首页 » 编程设计

c#之更改 WebFaultException 的内容类型

2024年01月01日43zhoujg

我有一个 WCF REST 服务,其接口(interface)方法用 [WebGet(..., ResponseFormat = WebMessageFormat.Json)] 注释并且通常提供 JSON 格式的响应。现在代码指示错误:

throw new WebFaultException<string>("helpful message",HttpStatusCode.BadRequest); 

问题是响应中的 Content-Type 仍然是 application/json,即使正文只是纯文本,而不是 JSON 编码。我可以创建一个助手来生成我的故障异常,它将设置 WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain";,但是如果 WCF 层中有一个快速修复,它只会设置这些类型的异常的内容类型将是可取的。执行此操作最干净的方法是什么?

请您参考如下方法:

您可以继承 WebFaultException 并在您的项目中使用它。

public class MyWebFaultException<T>:WebFaultException<T> 
{ 
    public MyWebFaultException(T message) 
        : base(message, HttpStatusCode.BadRequest) 
    { 
        WebOperationContext.Current.OutgoingResponse.ContentType = "text/plain"; 
    } 
}