zoukankan      html  css  js  c++  java
  • WCF .NET REST调用方式

    1通过WebClient或者Request实现,此方法略去

    2通过WCF Client调用

      a通过WebChannelFactory建Channel

      b通过Channel就可以直接调用服务端方法

    3代码

    WCF服务端和客户端都引用Contact库

     [ServiceContract]
        public interface IUserService : IBaseWCFService
        {
            [WebGet(UriTemplate = "userID={userID}")]
            [Description("根据UserID获取用户信息")]
            UserInfo GetUserInfo(string userID);
        }

    Client调用方式

    using (WebChannelFactory<IUserService> wcf = new WebChannelFactory<IUserService>(new Uri("http://ipv4.fiddler:30760/Services/UserService")))
                    {  
                        var channel = wcf.CreateChannel();
                        IClientChannel clientchanel = channel as IClientChannel;                   
                        channel.GetUserInfo(new Random().Next(1, 1000).ToString());
                    }

    WCF请求头设置,ContentType,Accept,这个的设置很让人头痛,查询了很多资料才找到实现方式

    通过OperationContextScope来实现

    直接代码

     using (WebChannelFactory<IUserService> wcf = new WebChannelFactory<IUserService>(endpoint))
                    {
                        var channel = wcf.CreateChannel();
                        IClientChannel clientchanel = channel as IClientChannel;
                        using (new OperationContextScope(channel as IContextChannel))
                        {
                            WebOperationContext.Current.OutgoingRequest.Headers.Add("APIKey", Guid.NewGuid().ToString());
                            WebOperationContext.Current.OutgoingRequest.ContentType = "json"; 

             WebOperationContext.Current.OutgoingRequest.Accept                      
                            channel.GetUserInfo(new Random().Next(1, 1000).ToString());
                        }                   
                    }

  • 相关阅读:
    12.1
    我的火车头
    头文件优化时间
    一些姿势
    CodeForces
    CodeForces
    [SDOI 2015] 约数个数和
    BZOJ
    [国家集训队] middle
    鹅的问题
  • 原文地址:https://www.cnblogs.com/rosanshao/p/2450734.html
Copyright © 2011-2022 走看看