wcf纯代码实现http服务

数据结构

public enum AgvUpgradeStep
    {
        VersionCheck = 0,
        Downloading = 1,
        Updating = 2,
        Booting = 3
    }
    public enum AgvUpgradeResult
    {
        Success = 0,
        Running = 1,
        Failed = 2
    }
    [DataContract]
    public class AgvUpgradeProgress
    {
        [DataMember]
        public AgvUpgradeStep step;
        [DataMember]
        public AgvUpgradeResult status;
        [DataMember]
        public string errinfo;
    }

 

 

1 定义协定

[ServiceContract]
    public interface TestHttpInterface
    {
        [OperationContract]
        [WebGet(UriTemplate = "DownloadFile")] //DownloadFile?Path={path}
        Stream DownloadFile();



        [WebInvoke(Method = "POST", UriTemplate = "TestJson", ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json)]
        [OperationContract]
        Stream TestJson(AgvUpgradeProgress progress);

    }

2 实现协定

[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class TestHttpService : TestHttpInterface
    {
        public string upgradeFile;
        public Stream DownloadFile()
        {
            if (WebOperationContext.Current == null) throw new Exception("WebOperationContext not set");
            if (string.IsNullOrEmpty(upgradeFile))
            {
                return null;
            }
            if (File.Exists(upgradeFile) == false)
            {
                return null;
            }
            var fileName = Path.GetFileName(upgradeFile);
            WebOperationContext.Current.OutgoingResponse.ContentType = "application/octet-stream";
            WebOperationContext.Current.OutgoingResponse.Headers.Add("content-disposition", "inline; filename=" + Uri.EscapeDataString(fileName));

            return File.OpenRead(upgradeFile);
        }

        public Stream TestJson(AgvUpgradeProgress progress)
        {
            JObject o = new JObject();
            o["ret"] = "ok";

            WebOperationContext.Current.OutgoingResponse.ContentType = "application/json; charset=utf-8";
            return new MemoryStream(Encoding.UTF8.GetBytes(o.ToString()));
        }
    }

3 创建/配置服务

 1 //创建服务
 2 var wcf_file_service = new TestHttpService;
 3 //创建服务主机 
 4 var file_service_host = new ServiceHost(wcf_file_service);
 5 //获取协定          
 6 var wcfcontract = ContractDescription.GetContract(typeof(AgvUpgradeHttpInterface));
 7 
 8 string address = @"http://0.0.0.0:8888";
 9 
10             var binding = new WebHttpBinding();
11             binding.MaxBufferPoolSize = 524288;
12             binding.MaxBufferSize = 67108864;
13             binding.MaxReceivedMessageSize = 67108864;
14             binding.TransferMode = TransferMode.Streamed;
15 
16             var serviceEndpoint = new ServiceEndpoint(wcfcontract, binding, new EndpointAddress(address));
17 
18             var httpBehavior = new WebHttpBehavior();
19             httpBehavior.DefaultOutgoingRequestFormat = WebMessageFormat.Json;
20             httpBehavior.DefaultOutgoingResponseFormat = WebMessageFormat.Json;
21             serviceEndpoint.EndpointBehaviors.Add(new WebHttpBehavior());
22 
23             file_service_host.AddServiceEndpoint(serviceEndpoint);
24 
25             var serviceMetadata = new ServiceMetadataBehavior();
26             serviceMetadata.HttpGetEnabled = true;
27             serviceMetadata.HttpsGetEnabled = true;
28             serviceMetadata.HttpGetUrl = new Uri($"{address}/services");
29             file_service_host.Description.Behaviors.Add(serviceMetadata);
30 
31 
32 
33             file_service_host.Opened += delegate { Console.WriteLine("WCF file server 已经启动!"); };
34             file_service_host.Open();
35 
36 //获取本机ip
37 /*            String strHostName = string.Empty;
38             IPHostEntry ipEntry = Dns.GetHostEntry(Dns.GetHostName());
39             IPAddress[] addr = ipEntry.AddressList;
40 
41             for (int i = 0; i < addr.Length; i++)
42             {
43                 Console.WriteLine("IP Address {0}: {1} ", i, addr[i].ToString());
44             }*/

 

posted @ 2021-10-19 22:36  wolbo  阅读(258)  评论(0编辑  收藏  举报