2014-02-18 78 views
0

我创建了Wcf服务。它将由Wcf客户端和非Wcf客户端访问。我为FaultException处理创建了我自己的类,如下所示;处理非WCF客户端的WCF故障

[DataContract] 
public class ErrorResponse 
{ 
    [DataMember] 
    public string ErrMsg {get;set;} 
} 

对于我的业务接口我有

[ServiceContract] 
public interface IService 
{ 
    [OperationContract] 
    [FaultContract (typeof(ErrorResponse))] 
    [WebInvoke(Method = "POST", UriTemplate = "/XML/GetTypes", BodyStyle = WebMessageBodyStyle.Bare)] 
    TypeResponse XMLTypes(TypeRequest TypeRequest); 
} 

在我的方法XmlTypes我有以下几点;

public static TypeResponse XmlTypes(TypeRequest TypeRequest) 
{ 
    //do something 
    //raise a error 

    ErrorResponse oErrorResponse = new ErrorResponse(); 
    oErrorResponse.ErrMsg = "Some Error happened"; 

    FaultCode oFaultCode = new FaultCode("12345"); 

    throw new FaultException<ErrorResponse>(oErrorResponse , new FaultReason ("Reason for the fault"), 
      new FaultCode("TypeRequestFailed", new FaultCode("TypeNotFound"))); 

对于Wcf客户端来说,这似乎工作正常。

但是,使用Web客户端UploadString(我知道我可以使用服务引用,这是用于测试目的)使得从非WCF客户的电话时,例如,我回来

System.Net.WebException: The remote server returned an error: (400) Bad Request.

这是我的另一个测试应用程序中的webclient代码;

WebClient oClient = new WebClient(); 

oClient.Encoding = UTF8Encoding.UTF8; 
oClient.Headers.Add("Content-Type", "application/xml"); 

try 
{ 
    txtResponse.Clear(); 

    sRequest = "<TypeRequest><UserId>1</UserId><Password>asdax12</Password></TypeRequest>"; 
    txtResponse.Text = oClient.UploadString("http://localhost:49562/Service.svc/XML/XmlTypes", "POST", sRequest).ToString(); 
} 
catch (Exception ex) 
{ 
    txtResponse.Text = ex.ToString(); 
} 

在我的webconfig文件我加入从这个例子throwing soap faults for non wcf clients

<system.serviceModel> 
    <bindings> 
    <customBinding> 
     <binding name="basicHttpSoap12Binding"> 
     <textMessageEncoding messageVersion="Soap12"/> 
     <httpTransport/> 
     </binding> 
    </customBinding> 
    </bindings> 
    <services> 
    <service name="MySoap12Service"> 
     <endpoint address="" binding="customBinding" bindingConfiguration="basicHttpSoap12Binding" 
     bindingNamespace="MySoap12ServiceNamespace" 
     contract="MySoap12Service"> 
     </endpoint> 
    </service> 
    </services> 
</system.serviceModel> 

我要去哪里错采取以下?

+0

你能举一个你如何使用'WebClient'的例子吗? – Tim

+0

我已更新我的问题 – Tommassiov

+0

如果您不抛出过错,会发生什么?故障意味着返回500错误,而不是400. –

回答

0

你有任何其他的网络方法,你可以成功呼叫? (来自同一个非WCF客户端)

由于你有一个400 http错误,在我看来,这个调用并不是以正确的方式构建或完成的,所以如果你可以在同一个服务中成功调用任何其他方法将帮助我们确保电话正确。

+0

如果我不引发FaultException,它会正常工作。 – Tommassiov

+0

所以这里有2个链接可能会有所帮助:http://dotnet.dzone.com/news/wcf-rest-tip-2也是这样的:http:// stackoverflow。com/questions/4461254/wcf-rest-services-generic-exception-handling – Jportelas

+0

我想为Wcf RestFul服务获取Xml或Json响应,是否可能 – Tommassiov