Last active
December 19, 2015 01:09
-
-
Save zhuqling/5873994 to your computer and use it in GitHub Desktop.
WCF在REST状态下,传递和获取Header
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 传递Header | |
using (WebChannelFactory<IService> wcf = new WebChannelFactory<IService>(new Uri("http://localhost:"+port+"/Web"))) | |
{ | |
IService channel = wcf.CreateChannel(); | |
// 首先创建OperationContextScope | |
// ** 注意OperationContextScope只能使用在单个调用内,不能跨调用包裹 ** | |
using ( OperationContextScope scope = new OperationContextScope((IContextChannel)channel)) | |
{ | |
// 传递Header | |
WebOperationContext.Current.OutgoingRequest.Headers.Add("X-MyHeaderName", "1234"); | |
// ... 调用 | |
} | |
} | |
// 使用Header | |
public class Service : IService | |
{ | |
public string EchoWithPost(string s) | |
{ | |
string token = WebOperationContext.Current.IncomingRequest.Headers["X-MyHeaderName"]; | |
return token + " ** You said " + s; | |
} | |
} | |
// 列出所有Header Field | |
using System.ServiceModel.Web; | |
protected override IEnumerable<KeyValuePair<string, SampleItem>> OnGetItems() { | |
WebHeaderCollection headers = WebOperationContext.Current.IncomingRequest.Headers; | |
foreach (string key in headers.Keys) { | |
logger.Debug("header " + key + "=" + headers[key]); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment