从服务器到客户端的WCF Restful POST返回错误消息

时间:2017-03-22 07:00:39

标签: c# rest wcf post

我需要一个关于如何将服务器上捕获的错误消息返回给客户端的建议。我正在创建WCF Restfull服务,并能够在使用GET方法时返回错误消息。但很难找到从POST方法返回错误消息的正确方法。

EDITED

对于@Abd:

我尝试过使用throw WebFaultException,如下面的代码:

 try
                    {
                        newbudgetid = _service.Create(budgettrx);
                    }
                    catch (Exception ex)
                    {
                        error_message = ex.Message;
                        MyCustomErrorDetail customerror = new MyCustomErrorDetail(
"Error", error_message);

                        throw new WebFaultException<MyCustomErrorDetail>(customerror, HttpStatusCode.NotFound);

                    }

这是课程定义:

public class MyCustomErrorDetail
    {
    public MyCustomErrorDetail(string errorInfo, string errorDetails)
        {
            ErrorInfo = errorInfo;
            ErrorDetails = errorDetails;
        }
        [DataMember]
        public string ErrorInfo { get; private set; }
        [DataMember]
        public string ErrorDetails { get; private set; }
    }

在客户端代码上,我该如何编写服务器的错误输出?

 BudgetTransactionRequest bt = new BudgetTransactionRequest
                {
                    transaction_code = "7PRM007690 ",
                    category = "Expenses",
                    claim_status = "Presales ID",
                    amount = "320000.00000",
                    application_type = "Payment Request",
                    opportunity = "BSMD000586",
                    project = null,
                    request_date = new DateTime(2013, 03, 09),
                    request_status = "Validated",
                    owner = "nurul.wiiyanti",
                };




                WebClient proxy = new WebClient();
                proxy.Headers["Content-Type"] = "application/json";
                MemoryStream ms = new MemoryStream();
                DataContractJsonSerializer serialize = new DataContractJsonSerializer(typeof(BudgetTransactionRequest));
                serialize.WriteObject(ms, bt);
                byte[] data = proxy.UploadData("http://10.10.64.19:8082/Service1.svc/CreateBudgetTransaction/", "POST", ms.ToArray());
                Stream stream = new MemoryStream(data);
                DataContractJsonSerializer obj = new DataContractJsonSerializer(typeof(BudgetTransactionRequest));

2 个答案:

答案 0 :(得分:0)

您可以创建一个ServiceResult类,并将其用于所有Get和Post方法。在此类中,您可以使用Generic Result,HasException,ExceptionMessage等属性。

答案 1 :(得分:0)

抛出WebFaultException(T errorDetail,HttpResponseCode代码)

在这里,您可以将响应类型设置为另一种对象类型,这是有意义的,并且您还可以设置所需的ResponseCode。

errorDetail必须是可序列化的

link可能有用,或者此link