【问题标题】:How do you reject a message in WCF?如何拒绝 WCF 中的消息?
【发布时间】:2017-02-20 23:14:55
【问题描述】:

我正在迁移到使用安全令牌对用户进行身份验证的 Azure。所以现在我在消息的标题中传递安全令牌并使用服务器端的 IDispatchMessageInspector 行为读取它。基本机制工作得很好,但是当令牌无法通过身份验证时,我需要拒绝它,就像它未能通过 UserNamePasswordValidator 一样。我如何完成这段代码的任何想法:

public object AfterReceiveRequest(ref Message request, IClientChannel channel, InstanceContext instanceContext)
{
    if (!this.IsAuthenticated(securityToken))
    {
        <Return Error Message Structure>
    }
}

【问题讨论】:

  • 这是基于 SOAP 还是 REST?
  • 没有肥皂,花生。两者我都会回答。
  • 对于 RESTful 服务,显而易见的做法是返回服务器 403 响应,并带有一个可选的响应正文,说明信息是什么。
  • 你试过在 if 块中抛出异常吗?

标签: wcf wcf-security


【解决方案1】:

简单的选择是抛出FaultException

object IDispatchMessageInspector.AfterReceiveRequest(ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel, System.ServiceModel.InstanceContext instanceContext)
{
    try
    {
        if (!this.IsAuthenticated(securityToken))
        {
           throw new FaultException<string>("some message");
        }
    }      
    catch (FaultException e)
    {
        throw new FaultException<string>(e.Message);
    }
    return null;
}

如果您想要更优雅的东西并控制返回的 HttpStatus 代码(默认为 500),那么您可以实现一个端点行为扩展,它注册一个调度消息检查器来监视故障。请参阅以下帖子:

http://www.shulerent.com/2016/05/31/returning-custom-http-status-codes-for-wcf-soap-exceptions/

【讨论】:

    猜你喜欢
    • 2013-10-16
    • 1970-01-01
    • 2018-12-31
    • 2016-11-08
    • 1970-01-01
    • 1970-01-01
    • 2015-05-24
    • 2019-12-20
    • 1970-01-01
    相关资源
    最近更新 更多