我正在使用 WCF Service 4.5 F/W 开发 REST Full API。请建议如何向客户发送异常或任何业务验证消息。我正在寻找一个非常通用的解决方案,请建议最好的方法。
我在下面尝试了一些方法,
这些没有按预期工作..
我的示例代码片段:
界面:
[OperationContract]
[FaultContract(typeof(MyExceptionContainer))]
[WebInvoke(Method = "GET", UriTemplate = "/Multiply/{num1}/{num2}", BodyStyle = WebMessageBodyStyle.Wrapped,RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml)]
string Multiply(string num1, string num2);
执行:
public string Multiply(string num1, string num2)
{
if (num1 == "0" || num2 == "0")
{
try
{
MyExceptionContainer exceptionDetails = new MyExceptionContainer();
exceptionDetails.Messsage = "Business Rule violatuion";
exceptionDetails.Description = "The numbers should be non zero to perform this operation";
//OutgoingWebResponseContext outgoingWebResponseContext = WebOperationContext.Current.OutgoingResponse;
//outgoingWebResponseContext.StatusCode = System.Net.HttpStatusCode.ExpectationFailed;
//outgoingWebResponseContext.StatusDescription = exceptionDetails.Description.ToString();
// throw new WebFaultException<MyExceptionContainer>(exceptionDetails,System.Net.HttpStatusCode.Gone);
throw new FaultException<MyExceptionContainer>(exceptionDetails,new FaultReason("FaultReason is " + exceptionDetails.Messsage + " - " + exceptionDetails.Description));
}
catch (Exception ex)
{
throw new FaultException(ex.Message);
}
}
return Convert.ToString(Int32.Parse(num1) * Int32.Parse(num2));
}
网络配置:
<system.serviceModel>
<services>
<service name="TestService.TestServiceImplementation" behaviorConfiguration="ServiceBehaviour">
<endpoint binding="webHttpBinding" contract="TestService.ITestService" behaviorConfiguration="webHttp" >
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="true"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name="webHttp" >
<webHttp helpEnabled="true" faultExceptionEnabled="true"/>
</behavior>
</endpointBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
客户 :
try
{
string serviceUrl = "http://localhost:51775/TestService.cs.svc/Multiply/0/0";
//Web Client
//WebClient webClient = new WebClient();
//string responseString = webClient.DownloadString(serviceUrl);
WebRequest req = WebRequest.Create(serviceUrl);
req.Method = "GET";
req.ContentType = @"application/xml; charset=utf-8";
HttpWebResponse resp = req.GetResponse() as HttpWebResponse;
if (resp.StatusCode == HttpStatusCode.OK)
{
XmlDocument myXMLDocument = new XmlDocument();
XmlReader myXMLReader = new XmlTextReader(resp.GetResponseStream());
myXMLDocument.Load(myXMLReader);
Console.WriteLine(myXMLDocument.InnerText);
}
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
这是我的第一个问题,感谢所有热情的开发人员..!
最佳答案
而不是 FaultException
,使用以下内容:
服务器:
catch (Exception ex)
{
throw new System.ServiceModel.Web.WebFaultException<string>(ex.ToString(), System.Net.HttpStatusCode.BadRequest);
}
客户:
catch (Exception ex)
{
var protocolException = ex as ProtocolException;
var webException = protocolException.InnerException as WebException;
if (protocolException != null && webException != null)
{
var responseStream = webException.Response.GetResponseStream();
var error = new StreamReader(webException.Response.GetResponseStream()).ReadToEnd();
throw new Exception(error);
}
else
throw new Exception("There is an unexpected error with reading the stream.", ex);
}
关于rest - WCF RESTFul 服务中的异常处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26070740/