用WCF项目模板写Restful风格的接口
前言:在百度逛了,现成的案例也有,但是想自己过一遍留有记忆。写完案例测试完,反思了一下,发现微软的webApi不就是他的升级版吗。比他好用,可以实现重载方法。首先WCF默认不能实现重载方法的(在接口类中)。如果是简单的WCF完全满足。
1.创建一个wcf项目模板。
可以选有默认代码的模板,可以改改就用,如果建的是空模板,那就得自己写一个简单的WCF实现。
2.改改默认的代码(关键的一步,接口类)这里提供了两种方法,一个是GET,另外是POST,都是简单的返回Json字符串
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace EricSunWcfService
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
[ServiceContract]
public interface IUserService
{
[OperationContract]
[WebInvoke(Method = "GET", UriTemplate = "getuser/{name}", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
UserData GetUserData(string name);
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "checkuser", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
UserData CheckUserData(UserData user);
}
}
3.剩下的继承接口的实现类没有什么值得注意的。照常就OK!
4. .svc文件右键‘视图标记’可以修改服务的实现类名称。(因为restful是基于http的,所以只能寄宿IIS)。
5. 修改配置文件(web.config),以适应http的浏览器访问。
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<appSettings>
<add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5"/>
</system.web>
<system.serviceModel>
<services>
<!-- 这里是关键,在wcf默认的情况下寄宿IIS中可以不用配这个,但是咱们是restful风格的不一样。尤其是 behaviorConfiguration="ESEndPointBehavior" 必须得有-->
<service name="EricSunWcfService.UserService" behaviorConfiguration="fff">
<endpoint address="" binding="webHttpBinding" contract="EricSunWcfService.IUserService" behaviorConfiguration="ESEndPointBehavior" >
</endpoint>
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="fff">
<!-- 为避免泄漏元数据信息,请在部署前将以下值设置为 false -->
<serviceMetadata httpGetEnabled="true" httpsGetEnabled="true"/>
<!-- 要接收故障异常详细信息以进行调试,请将以下值设置为 true。在部署前设置为 false 以避免泄漏异常信息 -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
<endpointBehaviors>
<!-- 这里就是上面用的终结点用的行为节点 -->
<behavior name="ESEndPointBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
<!--
若要在调试过程中浏览 Web 应用程序根目录,请将下面的值设置为 True。
在部署之前将该值设置为 False 可避免泄露 Web 应用程序文件夹信息。
-->
<directoryBrowse enabled="true"/>
</system.webServer>
</configuration>
6.最后就是测试,因为是wcf服务模板,所以也可以不用发布到iis上,直接单击vs上的启动按钮,就可以进行预览。
7.若在访问 http://localhost:8089/UserService.svc 的时候出现500.19【HTTP Error 500.19 - Internal Server Error】错误请参考如下链接解决(端口要看自己的情况)
http://www.cnblogs.com/mingmingruyuedlut/archive/2011/11/04/2235630.html
8.访问GET方法我们可以直接在浏览器地址栏中输入对应的service地址即可访问
例如输入 http://localhost:8089/UserService.svc/getuser/eric
会给我们返回: {“Email”:“test@123.com”,“Name”:“eric”,“Password”:null}
9.至于post的方法,可以用httpclient类/httpwebrequest类来实现调用。类似如下:
Uri ur = new Uri("http://localhost:1739/Service1.svc/posts");
HttpClient client = new HttpClient();
//var con = JsonConvert.SerializeObject(ff);//json序列化
HttpContent content = new StringContent("{\"BoolValue\":true,\"StringValue\":\"jfdi\"}");//请求体
content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");//请求头以及格式
var response = client.PostAsync(ur, content).Result;//异步post去请求
if(response.StatusCode== System.Net.HttpStatusCode.OK)
{
var context = response.Content.ReadAsStringAsync().Result;
Console.Write(context);
}
Console.ReadKey();
如果不成功看看传的请求体中的json串是否正确?
10.若是我们发现在调用PUT或者DELETE方法时出现Status:405 Method Not Allowed的问题,请在web.config文件中的system.webServer节点中添加如下配置
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
</handlers>