服务演示代码:
public class Login : UserNamePasswordValidator { public override void Validate(string userName, string password) { if (new ProjectContext().Users.Count(x => x.Username == userName && x.Password == password) == 0) { throw new FaultException("Invalid login"); } } }
客户代码演示:
internal bool LoginOnWcf(string address, string password) { try { service.ClientCredentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None; service.ClientCredentials.UserName.UserName = address; service.ClientCredentials.UserName.Password = password; user = service.GetUserById(address); return true; } catch (FaultException ex) { MessageBox.Show(ex.Message); return false; } }
Web.config演示:
当我扔FaultException
,服务崩溃.我希望能够抓住FaultException
客户端并保持服务正常运行.
我希望能很好地解释我的问题并提供必要的代码.
WCF使用Faults将错误从服务器抛出到客户端.您可以使用a FaultException
启动,然后根据需要创建自己的自定义故障.
因此,在您的示例中,您可以简单地执行以下操作.
throw new FaultException("Invalid login")
该文章提供了有关如何使用WCF实现故障一大堆更多细节.