Jac*_*cob 4 rest wcf http http-status-codes
如何让我的WCF服务以RESTful方式传达错误?具体来说,如果调用者将无效的查询字符串参数传递给我的方法,我希望将400或404 HTTP错误返回给用户.当我搜索与WCF相关的HTTP错误状态时,我所能找到的只是人们试图解决他们收到的错误的页面.我宁愿不只是抛出一个FaultException,因为它会转换为500错误,这不是正确的状态代码.
我在这里找到了一篇有用的文章:http://zamd.net/2008/07/08/error-handling-with-webhttpbinding-for-ajaxjson/.基于此,这就是我提出的:
public class HttpErrorsAttribute : Attribute, IEndpointBehavior
{
    public void AddBindingParameters(
        ServiceEndpoint endpoint, 
        BindingParameterCollection bindingParameters)
    {
    }
    public void ApplyClientBehavior(
        ServiceEndpoint endpoint, ClientRuntime clientRuntime)
    {
    }
    public void ApplyDispatchBehavior(
        ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
    {
        var handlers = endpointDispatcher.ChannelDispatcher.ErrorHandlers;
        handlers.Clear();
        handlers.Add(new HttpErrorHandler());
    }
    public void Validate(ServiceEndpoint endpoint)
    {
    }
    public class HttpErrorHandler : IErrorHandler
    {
        public bool HandleError(Exception error)
        {
            return true;
        }
        public void ProvideFault(
            Exception error, MessageVersion version, ref Message fault)
        {
            HttpStatusCode status;
            if (error is HttpException)
            {
                var httpError = error as HttpException;
                status = (HttpStatusCode)httpError.GetHttpCode();
            }
            else if (error is ArgumentException)
            {
                status = HttpStatusCode.BadRequest;
            }
            else
            {
                status = HttpStatusCode.InternalServerError;
            }
            // return custom error code.
            fault = Message.CreateMessage(version, "", error.Message);
            fault.Properties.Add(
                HttpResponseMessageProperty.Name,
                new HttpResponseMessageProperty
                {
                    StatusCode = status,
                    StatusDescription = error.Message
                }
            );
        }
    }
}
这允许我[HttpErrors]向我的服务添加属性.在我的自定义错误处理程序中,我可以确保发送我要发送的HTTP状态代码.
| 归档时间: | 
 | 
| 查看次数: | 4274 次 | 
| 最近记录: |