首页 > 代码库 > 调用WCF不需要添加服务引用,使用一个WCFHelper类就可以

调用WCF不需要添加服务引用,使用一个WCFHelper类就可以

效果图:

 

 

 

调用过程:

 string WCFURL = "http://localhost:100/Service1.svc";            UserRequest user = new UserRequest { UserName = UserName.Text, Address = Address.Text, Email = Email.Text };            string request = "{\"request\":" + new JavaScriptSerializer().Serialize(user) + "}";            string returnContent = WCFHelper.SendHttpRequest(WCFURL, "GetUserInfo", request);            UserResult re = new JavaScriptSerializer().Deserialize<UserResult>(returnContent);            lblText.Text = re.Result;

 

WCF项目中配置文件节点配置: 

 1 <system.serviceModel> 2     <behaviors> 3       <endpointBehaviors> 4         <behavior name="httpBehavior"> 5           <webHttp /> 6         </behavior> 7       </endpointBehaviors> 8       <serviceBehaviors> 9         <behavior name="">10           <serviceMetadata httpGetEnabled="true" />11           <serviceDebug includeExceptionDetailInFaults="false" />12         </behavior>13       </serviceBehaviors>14     </behaviors>15     <services>16       <service name="WCFServices.Service1">17         <endpoint address=""18                   behaviorConfiguration="httpBehavior"19                   binding="webHttpBinding"20                   contract="WCFServices.IService1" />21       </service>22     </services>23   </system.serviceModel>
View Code

 

 

WCF项目请求接口:

 [ServiceContract]    public interface IService1    {        [OperationContract]        [WebInvoke(Method = "POST", UriTemplate = "GetUserInfo",            BodyStyle = WebMessageBodyStyle.WrappedRequest, //包装请求,但不包装相应  注:如果设置为包装相应,返回的JSON结果会加一个 壳            ResponseFormat = WebMessageFormat.Json,            RequestFormat = WebMessageFormat.Json)]        UserResult GetUserInfo(UserRequest request);    }
View Code

 

 

WCF项目实现方法:

  public UserResult GetUserInfo(Model.UserRequest request)        {            return new UserResult { Result = request.UserName + "地址是:" + request.Address + ",邮箱是:" + request.Email };        }
View Code

 

 

项目下载地址: http://download.csdn.net/detail/vincent_void/7676403