UserNamePasswordValidator向客户端发送自定义错误消息

时间:2015-02-16 16:22:43

标签: c# wcf

我有一个实现UserNamePasswordValidator的自定义用户验证器。 此验证器使用WCF调用另一个身份验证Web服务来验证用户。

它工作正常,但我想向最终客户端抛出一个自定义消息,以防身份验证服务调用(在中间服务器端)由于某种原因失败(FaultException,CommunicationException,TimeoutException或任何其他异常)。 / p>

我在客户端上获取的所有内容始终都是相同的消息弹出窗口,告知身份验证基本失败。

如何将自定义消息返回给客户端(作为FaultException或任何其他方式)?

class CustomUserNameValidator : UserNamePasswordValidator
{
    public override void Validate(string userName, string password)
    {
        try {
            string domain="";
            string userNameOnly;

            //Parse userName to extract domain and userNameOnly
            if(userName.Contains('\\')) {
                String[] splitted = userName.Split('\\');
                domain = splitted[0];
                userNameOnly = splitted[1];
            }
            else {
                userNameOnly = userName;
            }

            //throw new FaultException("Test fault exception from CustomUserNameValidator");

            //Get the authentication service
            ServiceReference1.AuthWSClient service = new ServiceReference1.AuthWSClient("AuthWSPort");

            //Call the athentication service
            ServiceReference1.user user = service.connect(domain, userNameOnly, password); 

            //TODO: Catch exceptions (invalid user throws one)
            //throw new SecurityTokenValidationException("Authentication failed for \"" + userName + "\"");
        }
        catch (FaultException ex)
        {
            //throw new FaultException("Authentication service (called from ATLAS server) returned an error: \n\n" + ex.Message);
            throw new SecurityTokenValidationException("Authentication service (called from ATLAS server) returned an error: \n\n" + ex.Message);
        }
        catch (CommunicationException ex)
        {
            //throw new FaultException("Communication issue with authentication service (called from ATLAS server): \n\n" + ex.Message);
            throw new SecurityTokenValidationException("Communication issue with authentication service (called from ATLAS server): \n\n" + ex.Message);
        }
        catch (TimeoutException ex)
        {
            //throw new FaultException("Connection with authentication service (called from ATLAS server) has timed out: \n\n" + ex.Message);
            throw new SecurityTokenValidationException("Connection with authentication service (called from ATLAS server) has timed out: \n\n" + ex.Message);
        }
        //catch (Exception ex)
        //{
        //    //Unexpected exception
        //    log.LogError(ex.ToString());
        //    throw;
        //}
    }
}

客户端有类似的try / catch块,但看起来它没有用于UserNamePasswordValidator:似乎有一个特定的WCF内部捕获来自UserNamePasswordValidator的错误。

1 个答案:

答案 0 :(得分:1)

Validate的{​​{1}}方法中抛出异常时,异常将被包装为UserNamePasswordValidator的{​​{1}}(来自InnerException包) ,这是你必须抓住客户端的类型:

MessageSecurityException

我希望它会有所帮助。