其它的先放一边。今天先来分享一下前段时间给公司做网站WCF服务接口的心得。
配置文件的配置问题
这里既然讨论WCF配置文件的问题,那么怎么创建的就不一一讲解了。好多博主都有提过的。所以直接分享自己开发时的收获,这里感谢好多给我启发的人,@好多人....
我这里就拿登录接口来分享下吧。
先贴出代码。
这是服务端代码
因为ASP的兼容性问题,这里的AspNetCompatibilityRequirementsMode用Allowed,(----2018-03-30修改——其实这里需要打开ASP兼容是因为在配置文件里把它给打开了,不配置也是OK的。-----)
(这里说一下,因为前段用Ajax调的接口,所以用了callback)-------还是跨域的问题。
namespace WCFService.Services
{
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码、svc 和配置文件中的类名“Login”。
// 注意: 为了启动 WCF 测试客户端以测试此服务,请在解决方案资源管理器中选择 Login.svc 或 Login.svc.cs,然后开始调试。
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[JavascriptCallbackBehavior(UrlParameterName = "jsoncallback")]
public class Get_Login : ILogin
{
/// <summary>
/// 登录
/// </summary>
/// <param name="id"></param>
/// <param name="pwd"></param>
/// <returns></returns>
string ILogin.Login(string id, string pwd)
{
return BLL.LoginBLL.Instance.Login(id, pwd);
}
}
}
这是契约代码
namespace WCFService.IBLL
{
// 注意: 使用“重构”菜单上的“重命名”命令,可以同时更改代码和配置文件中的接口名“ILogin”。
[ServiceContract]
public interface ILogin
{
[OperationContract]
[WebInvoke(
Method = "GET",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare,
UriTemplate = "/Login?id={id}&pwd={pwd}")]
string Login(string id, string pwd);
}
}
服务契约这里使用的是Get方法
先配置服务的ABC
A. address为空就行
B. binding这里我们绑定为webhttpbinding(因为前端是H5,所以只能用http请求,其它按情况而定)
C. contract绑定的服务契约(当然啦,这里绑定的就是我们上面的ILogin)
ABC配置完成后基本的WCF服务已经是可以使用了的。但是我们这里讲解的它的跨域问题,WCF最主要的还是配置问题。这个是关键。接下来我们说说这个跨域问题。
配置跨域
如需跨域的话要配置下面几点(仅供参考)
服务配置也贴出来吧
<!--登录-->
<service name="Dar.WCFService.Services.Get_Login">
<endpoint address="" behaviorConfiguration="web" binding="webHttpBinding"
bindingConfiguration="HttpJsonBinding" contract="Dar.WCFService.IBLL.ILogin" />
</service>
这里说一下跨域除了配置ABC外还要加bindingConfiguration属性,binding配置为webHttpBinding,以下是为bindingConfiguration配置允许跨域
<!--指定脚本可以跨域-->
<bindings>
<webHttpBinding>
<binding name="HttpJsonBinding" crossDomainScriptAccessEnabled="true"/>
</webHttpBinding>
</bindings>
接下来配置服务行为
<behaviors>
<endpointBehaviors>
<behavior name="web">
<!-- 配置指定允许web脚本访问-->
<webHttp/>
<!--<enableWebScript />-->
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="">
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
这里顺带说一下。
aspNetCompatibilityEnabled和multipleSiteBindingsEnabled都要设置为true
有点累了,睡个午觉。就先讲那么多,萌新一个。对WCF只是了解了些基础。哪里不对的望各位大神指点(勿喷!)。有什么我们多多交流。