我的客户端没有捕获泛型FaultException。
我的服务合同:
[ServiceContract]
public interface IEmpresaWebService
{
[OperationContract]
[FaultContract(typeof(ValidationExceptionDTO))]
EmpleadoEmpresaDTO Login(string username, string password);
}
我的服务
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class EmpresaWebService : IEmpresaWebService
{
private readonly IUnitOfWork _UnitOfWork;
public EmpresaWebService(IUnitOfWork UnitOfWork) {
this._UnitOfWork = UnitOfWork;
//SeedingBootsrapper.RegisterSeedings();
//var initializer = new CustomDataInitializer<PsicotecnicosContext>(new string[] { "*" });
//Database.SetInitializer<PsicotecnicosContext>(initializer);
}
public EmpleadoEmpresaDTO Login(string username, string password) {
var EmpleadoEmpresaService = this._UnitOfWork.GetService<EmpleadoEmpresaService>();
EmpleadoEmpresaDTO empleadoEmpresaDTO = new EmpleadoEmpresaDTO();
try {
var empleado = EmpleadoEmpresaService.ValidarLogin(username, password);
Mapper.CreateMap<EmpleadoEmpresa, EmpleadoEmpresaDTO>();
empleadoEmpresaDTO = Mapper.Map<EmpleadoEmpresa, EmpleadoEmpresaDTO>(empleado);
}
catch (ValidationException Ex) {
throw new FaultException<ValidationExceptionDTO>(new ValidationExceptionDTO(Ex.Errors));
}
return empleadoEmpresaDTO;
}
}
尝试序列化的类
[DataContract]
public class ValidationExceptionDTO
{
[DataMember]
private Dictionary<string, string> _errors = new Dictionary<string, string>();
public ValidationExceptionDTO(IList<ValidationFailure> Errors) {
foreach (var validation in Errors) {
this._errors.Add(validation.ErrorMessage, validation.PropertyName);
}
}
[DataMember]
public Dictionary<string,string> Errors {
get {
if (this._errors != null) {
return this._errors;
}
else {
return new Dictionary<string,string>();
}
}
}
}
我的客户:
public class CuentasController : Controller
{
// GET: /Candidatos/Cuentas/
public ActionResult Index()
{
return View();
}
public ActionResult Login() {
return View();
}
[HttpPost]
public ActionResult Login(string username, string password, bool recordarme) {
try {
EmpresaServiceProxy.EmpresaWebServiceClient client = new EmpresaServiceProxy.EmpresaWebServiceClient();
EmpleadoEmpresaDTO empleadoEmpresa = client.Login(username, password);
var AutenticationProvider = new AuthenticationProvider(this.HttpContext);
AutenticationProvider.LoginAs(username, recordarme);
}
catch (FaultException<ValidationExceptionDTO> ex) {
}
catch(FaultException ex){
//only cath here
}
if (ModelState.IsValid) {
return RedirectToAction("Prueba");
}
return View();
}
[Authorize]
public string Prueba() {
return "Esta logeado";
}
}
}
答案 0 :(得分:1)
标准C#异常处理代码不允许您这样做,因此您必须抓住所有FaultExceptions
并使用GetType方法和严格Type comparison来过滤它们:< / p>
catch(FaultException ex)
{
if (ex.GetType().Equals(typeof(FaultException))) // Strict comparison of type
{
// Handle only FaultException exceptions, not its descendants
}
else
throw;
}
只是不要忘记抛出(或不抛出取决于你的要求)异常(谢谢@DStanley)