我为我的服务实现了一个IErrorHandler,如果授权错误,则需要返回403而不是400.
这就是我的ProvideFault方法的样子:
这就是我的ProvideFault方法的样子:
public void ProvideFault(Exception error,MessageVersion version,ref Message fault) { if (((FaultException)error).Code.SubCode.Name == "FailedAuthentication") { WebOperationContext.Current.OutgoingResponse.StatusCode = HttpStatusCode.Forbidden; WebOperationContext.Current.OutgoingResponse.StatusDescription = "StatusCode is forced to change in order to have the correct response on authentication."; } }
我想知道是否有任何方法可以为错误及其状态代码编写更好的检查,或者如何获得授权异常而不是FaultException女巫更通用?我觉得在FailedAuthentication字符串之后检查不太好,事实上它的授权不是认证…
解决方法
如果您使用的是C#6.0及更高版本,则可以使用
Exception Filters.示例为:
public string Example() { try { /* Method Logic */ return string.Empty; } catch (System.Net.Http.HttpRequestException e) when (e.Message.Contains("400")) { return "unauthorized"; } }
在你的情况下:
public string Example() { try { /* Method Logic */ return string.Empty; } catch (System.Net.Http.HttpRequestException e) when (e.Message.Contains("400")) { ProvideFault(e,"",e.Message); } } public void ProvideFault(System.Net.Http.HttpRequestException error,ref Message fault) { /* your logic according to your needs. */ }
原文地址:https://www.jb51.cc/csharp/99349.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。