[英]Return a custom error message in WCF http service
我剛開始使用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");
}
}
}
目前,如果用戶沒有訪問權限,則此操作僅返回一個空對象。 我嘗試拋出FaultException,但是沒有運氣。 理想情況下,我希望它以JSON格式返回,例如:
{
error: "User does not have access to patient record"
}
您必須使用Channel Dispatcher添加錯誤處理程序並定義自定義故障約定。
關於WCF 3.5中的錯誤處理,有一篇不錯的文章。 由於發布網址受到了懲罰,因此描述您的需求是很長的路要走。 我建議您在代碼項目中查找“ WCF錯誤處理和故障轉換”。 Sasha Goldshtein撰寫的一篇好文章。 希望這可以幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.