在WCF http服务中返回自定义错误消息
本文关键字:自定义 错误 消息 返回 WCF http 服务 | 更新日期: 2023-09-27 18:22:08
我刚开始学习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"
}
您必须使用Channel Dispatcher添加错误处理程序并定义自定义故障契约。
有一篇关于WCF 3.5中错误处理的好文章。这是很长的路来描述你需要什么,因为我被惩罚张贴网址。我建议您在代码项目中查找"WCF错误处理和故障转换"。萨莎·戈德斯坦写的一篇好文章。希望这能有所帮助。