WCF, HTTP, HTTPS, RESTful 使用

WCF 是个好东西,使用方便,麻烦的只是各种配置
不小心就会出各种各样的问题
今天来总结下,为了方便说明,异常就不详细区分了,直接Exception

下边的Add方法要额外使用REST,所以加了点注解
public interface IService
{
[OperationContract]
[FaultContract(typeof(Exception))]
[WebInvoke(Method = “POST”, ResponseFormat = WebMessageFormat.Xml, RequestFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare, UriTemplate = “Add”)]
EchangeOut Add(BonDto bonInfo);

[OperationContract]
[FaultContract(typeof(Exception))]
byte[] Get(decimal id);
}

实现类就不说了,自己想像

***********************************************************************
添加两个svc 文件,一个用于http, 一个用于https
然后设置 web.config 添加两个endpoint 与之对应
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name=””>
<serviceMetadata httpGetEnabled=”true” />
<serviceDebug includeExceptionDetailInFaults=”true” />
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<behavior name=”web”>
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>

<bindings>
<webHttpBinding>
<binding name=”ServiceBinding0″ maxReceivedMessageSize=”1024000000″>
</binding>
</webHttpBinding>

<basicHttpBinding>
<binding name=”SecureHttpBinding”>
<security mode=”Transport”>
<transport clientCredentialType=”None”/>
</security>
</binding>
</basicHttpBinding>
</bindings>

<serviceHostingEnvironment aspNetCompatibilityEnabled=”true” multipleSiteBindingsEnabled=”true” />
<services>
<service name=”Service.Http”>
<endpoint address=”” binding=”webHttpBinding” contract=”Service.WS.Contract.IService” behaviorConfiguration=”web” bindingConfiguration=”ServiceBinding0″/>
<endpoint address=”mex” binding=”mexHttpBinding” contract=”IMetadataExchange” />
</service>
<service name=”Service.Https”>
<endpoint address=”” binding=”basicHttpBinding” contract=”Service.WS.Contract.IService” bindingConfiguration=”SecureHttpBinding”/>
<endpoint address=”mex” binding=”mexHttpBinding” contract=”IMetadataExchange” />
</service>
</services>
</system.serviceModel>

注意上边webHttpBinding 和 basicHttpBinding 的使用

***********************************************************************
客户端使用
1: 在VS 里添加Service Reference,会生成下边这样的内容
如果不是,可以根据需要手改
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name=”BasicHttpBinding_Http” closeTimeout=”00:11:00″
openTimeout=”00:11:00″ receiveTimeout=”00:10:00″ sendTimeout=”00:11:00″
allowCookies=”false” bypassProxyOnLocal=”false” hostNameComparisonMode=”StrongWildcard”
maxBufferPoolSize=”524288″ maxBufferSize=”65536″ maxReceivedMessageSize=”65536″
textEncoding=”utf-8″ transferMode=”Buffered” useDefaultWebProxy=”true” messageEncoding=”Text”>
<readerQuotas maxDepth=”32″ maxStringContentLength=”8192″ maxArrayLength=”16384″
maxBytesPerRead=”4096″ maxNameTableCharCount=”16384″ />
<security mode=”None”>
<transport clientCredentialType=”None” proxyCredentialType=”None” realm=”” />
<message clientCredentialType=”UserName” algorithmSuite=”Default” />
</security>
</binding>

<binding name=”BasicHttpBinding_Https” maxReceivedMessageSize=”50000000″ maxBufferSize=”50000000″>
<security mode=”Transport” />
</binding>
</basicHttpBinding>
</bindings>

<client>
<endpoint address=”http://localhost:80000/service/ServiceHttp.svc&#8221;
binding=”basicHttpBinding” bindingConfiguration=”BasicHttpBinding_Http”
contract=”ServiceHttpTest.IService” name=”Service_Http” />

<endpoint address=”https://localhost/service/ServiceHttps.svc&#8221;
binding=”basicHttpBinding” bindingConfiguration=”BasicHttpBinding_Https”
contract=”ServiceHttpTest.IService” name=”Service_Https” />
</client>
</system.serviceModel>

页面就可以调用服务里相应的功能了
有一个问题就是Get 方法只能通过https 方式使用

***********************************************************************
2: Restful 方式,格式就像下边这样,主要就是拼XML
try
{
ServicePointManager.ServerCertificateValidationCallback = (sender, cert, chain, error) => true;
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(serverURL);
req.Method = “POST”;
req.ContentType = “application/xml; charset=utf-8”;
req.Timeout = 30000;
req.Headers.Add(“SOAPAction”, serverURL);

var xmlDoc = new XmlDocument { XmlResolver = null };
xmlDoc = GenerateXML();
string sXml = xmlDoc.InnerXml;
sXml = sXml.Replace(” xmlns=\”\””, “”);
req.ContentLength = System.Text.Encoding.UTF8.GetByteCount(sXml);//sXml.Length;
using (var sw = new StreamWriter(req.GetRequestStream()))
{
sw.Write(sXml);
}

using (HttpWebResponse res = (HttpWebResponse)req.GetResponse())
{
using (Stream responseStream = res.GetResponseStream())
{
using (var streamReader = new StreamReader(responseStream))
{
var soapResonseXmlDocument = new XmlDocument();
soapResonseXmlDocument.LoadXml(streamReader.ReadToEnd());

if (soapResonseXmlDocument.InnerXml != “ok”)
{
ret = false;
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}

基本应该都正常了,
注意的是https 在VS 自带的server 运行不了
所以要用IIS
确定你的 IIS 里的设置一切正常

iis_https

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s