我刚刚开始使用C#而且我对它有点困惑。
当用户无权访问特定资源时,我需要返回自定义错误消息。
服务的接口类:
[ServiceContract]
public interface IPatientDemographics
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "GetPatientDemographics/{strHospId}/{strView=mobile}",
ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)]
[return: MessageParameter(Name = "PatientDemographicsResultSet")]
List<PatientDemographics> GetPatientDemographics(string strHospId, string strView);
[OperationContract]
[FaultContract(typeof(AccessError))]
[return: MessageParameter(Name = "Error")]
AccessError ReturnAccessError();
}
[DataContract]
public class AccessError
{
[DataMember]
public bool Error { get; set; }
[DataMember]
public string Message { get; set; }
}
服务类:
[ServiceBehavior(AddressFilterMode=AddressFilterMode.Any)]
public class PatientDemographics : IPatientDemographics
{
public List<PatientDemographics> GetPatientDemographics(string strHospId, string strView)
{
AuthenticationDAO authenticationDAO = new AuthenticationDAO();
string userName = GetUserNameFromHeader();
if (authenticationDAO.CheckPatientSealAccess(strHospId, userName, "-1", "N"))
{
PatientDAO patientDAO = new PatientDAO();
patientDAO.AuditPatient(strHospId, userName);
return patientDAO.GetPatientDemographics(strHospId);
}
else
{
AccessError serviceData = new AccessError();
serviceData.Error = true;
serviceData.Message = "User does not have access to patient record";
throw new FaultException<AccessError>(serviceData, "User does not have access to patient record");
}
}
}
目前,如果用户没有访问权限,则只返回一个null对象。我尝试抛出一个FaultException,但没有运气。理想情况下,我希望它以JSON格式返回,如:
{
error: "User does not have access to patient record"
}
答案 0 :(得分:0)
您必须使用Channel Dispatcher添加错误处理程序并定义自定义错误契约。
在WCF 3.5中有关于错误处理的好文章。由于我因发布网址而受到处罚,因此描述您需要的内容还有很长的路要走。我建议你查看代码项目 “WCF错误处理和故障转换”。 Sasha Goldshtein写的一篇好文章。 希望这会有所帮助。