• 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());
                        }                   
                    }

  • 相关阅读:
    [NOI Online 提高组]序列
    微积分(下)
    微积分(上)
    [FJOI2018]领导集团问题
    [HNOI2015]亚瑟王
    [THUWC2017]随机二分图
    【模板】K级祖先(长链剖分)
    [CF438E]The Child and Binary Tree
    [洛谷P4841][集训队作业2013]城市规划
    [洛谷P4389]付公主的背包
  • 原文地址:https://www.cnblogs.com/rosanshao/p/2450734.html
Copyright © 2020-2023  润新知