自定义 WCF Rest 错误响应 [英] Customize WCF Rest error responses

查看:62
本文介绍了自定义 WCF Rest 错误响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了一个 WCF REST API 供第三方使用.我想做的一件事是,如果出现任何问题,将自定义错误响应返回给客户端.我不希望 WCF 默认错误页面显示发生了内部服务器错误或未找到方法名称.

I have written a WCF REST API for third-party use. One of the things I want to do is to return custom error responses to clients if anything goes wrong. I don't want the WCF default error page showing that internal server error has occurred or method name not found.

为此,我会在必要时抛出 WebFaultException.这将向客户端返回以下类型的响应:

To do so I throw WebFaultException<Error> where necessary. This return the following type of response to the client:

<Error>
  <type>MissingTag</type>
  <Desc>Tag 349 is missing</Desc>
</Error>

但是,如果发生任何其他类型的错误,例如序列化错误或未找到方法"错误或我想检查 POST、PUT 和 PATCH 是否存在 http 标头内容类型的位置,我该如何处理.我也想在那里抛出 WebFaultException<> .我尝试查看 IErrorHandler 但无法使其正常工作.

But how can I handle if any other type of error occurs like a serialization error or the "Method not found" error or place where I want to check that POST, PUT and PATCH have http header content-type present. I want to throw WebFaultException<> there too. I tried looking into IErrorHandler but could not get it working.

任何人都知道如何实现这种类型的事情.我也可以用一个简单的代码来演示 IErrorHandler 的用法吗?

Any one got ideas on how to implement this type of thing. Also can I have a simple code demonstrating the IErrorHandler usage?

推荐答案

您可以查看 Message Inspectors BeforeSendReply 用于自定义需要发送给客户端的回复

You can look into Message Inspectors BeforeSendReply for customizing the reply that needs to be sent to the client

如果在发出请求时未设置内容类型,您可以查看 AfterReceiveRequest,您可以在其中自定义收到的请求,然后根据需要进行操作.

If the content-type is not set when the request is made you can look into the AfterReceiveRequest where in you can customise the request received and then action as needed.

这篇关于自定义 WCF Rest 错误响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆