[個人筆記] WCF的小撇步

  • 345
  • 0
  • WCF
  • 2016-01-19

處理Http headers,資料Null時不回傳空Tag,回傳HttpCode

Sample Code記錄:

        [DataContract]
        public class Person
        {
            //EmitDefaultValue = false will make data member won't be serialized if it's null. 
            [DataMember(EmitDefaultValue = false)]
            public string ID { get; set; }
            [DataMember(EmitDefaultValue = false)]
            public string FirstName { get; set; }
            [DataMember(EmitDefaultValue = false)]
            public string LastName { get; set; }
            [DataMember(EmitDefaultValue = false)]
            public string City { get; set; }
        }
     
        public class Service1 : IService1
        {
            public string GetData(int pValue)
            {
                string tValue = string.Empty;
                MessageHeader tHeader = MessageHeader.CreateHeader("ReturnCode", "ns", "200");
                //建立一個回傳的Http Header 
                OperationContext.Current.OutgoingMessageHeaders.Add(tHeader);
                
                WebOperationContext tContext = WebOperationContext.Current;
                //建立回傳的HttpStatusCode
                tContext.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
     
                //檢查收到的呼叫是否含有IPHeader這個Http Header 
                int tNum = OperationContext.Current.IncomingMessageHeaders.FindHeader("IPHeader", "ns");
                if (tNum >= 0)
                {
                    tValue = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>(tNum);
                }
     
                return string.Format("You entered: {0} and IPHeader is {1}", pValue, tValue);
            }       
        }

完整參考來源:

Can't get client IP address on Vista and Windows 2008 server

Adding Header to .Net 3.5 WCF Client

how to not return null when a Data member field is not set in the data contract

WCF 測試用戶端 (WcfTestClient.exe)

How can I return a custom HTTP status code from a WCF REST method?

WCF REST: How to add a response header