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

  • 相关阅读:
    FluentValidation 验证框架笔记1
    AutoMapper 笔记1
    MediatR框架笔记1
    vscode调试python时提示无法将“conda”项识别为 cmdlet、函数、脚本文件或可运行程序的名称的解决方法
    Selenium使用自带浏览器自动化
    Selenium启动Chrome插件(Chrome Extensions)
    Gitee,Github 图片转直链
    CentOS 7.3 修改root密码 passwd: Authentication token manipulation error
    阿里云服务器 被入侵植入dhpcd导致cpu飙升100%问题
    Github 切换分支
  • 原文地址:https://www.cnblogs.com/rosanshao/p/2450734.html
Copyright © 2011-2022 走看看