在上一篇中编写了文件的上传.但是在整个服务中是禁用了服务的元数据的.只能使用http的方式进行调用.
下面我们来修改服务,使其可以通过引用服务的方式来进行调用.
首先,我们修改配置文件web.config.添加绑定代码如下图:
<system.serviceModel> <bindings> <webHttpBinding> <binding name="webBinding" closeTimeout="00:40:00" receiveTimeout="00:40:00" sendTimeout="00:40:00" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" useDefaultWebProxy="false" > <security mode="None"></security> <readerQuotas maxDepth="32" maxArrayLength="2147483647" maxStringContentLength="2147483647" maxBytesPerRead="2147483647"/> </binding> </webHttpBinding> <basicHttpBinding> <binding name="baseBinding" closeTimeout="00:40:00" receiveTimeout="00:40:00" sendTimeout="00:40:00" maxBufferSize="2147483647" maxReceivedMessageSize="2147483647" useDefaultWebProxy="false" > <security mode="None"></security> <readerQuotas maxDepth="32" maxArrayLength="2147483647" maxStringContentLength="2147483647" maxBytesPerRead="200000"/> </binding> </basicHttpBinding> </bindings> <services> <service name="WcfServiceTest.Service1" behaviorConfiguration="baseBehavior"> <endpoint address="" behaviorConfiguration="webBehavior" binding="webHttpBinding" bindingConfiguration="webBinding" contract="WcfServiceTest.IService1"> </endpoint> <endpoint contract="WcfServiceTest.IService1" bindingConfiguration="baseBinding" binding="basicHttpBinding" address="mex" behaviorConfiguration="baseBehavior"/> </service> </services> <behaviors> <endpointBehaviors> <behavior name="webBehavior"> <!--这里必须设置--> <webHttp helpEnabled="true"/> </behavior> <behavior name="baseBehavior"> </behavior> </endpointBehaviors> <serviceBehaviors> <behavior name="baseBehavior"> <serviceMetadata httpGetEnabled="True"/> </behavior> </serviceBehaviors> </behaviors> </system.serviceModel>
在浏览器里面浏览,会报错:
要使操作 UpLoad 中的请求成为流,操作必须具有其类型为 Stream 的单个参数。
按照错误提示,把参数变为一个.重新生成.运行正常.
[WebInvoke(Method = "POST", UriTemplate = "UpLoad", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)] [System.ComponentModel.Description("上传文件")] bool UpLoad(System.IO.Stream stream);
我们在控制台应用程序中添加服务应用.来测试一下.结果如下图:
测试代码
private static void GetUserByIdSoap(string id) { ServiceTest.Service1Client client = new Service1Client(); var result = client.GetUserById(id); Console.WriteLine(result.GetType()); Console.WriteLine("Id:{0};姓名:{1};性别:{2}", result.Id, result.Name, result.Gender == 1 ? "男" : "女"); }
其他的方法就不写了.都差不多的.