Ron Jacobs 有篇文章介绍如何在WCF Rest Service中使用API Key验证:http://blogs.msdn.com/b/rjacobs/archive/2010/06/14/how-to-do-api-key-verification-for-rest-services-in-net-4.aspx ,在WCF Data Service中怎么做呢?本文将介绍如何在WCF Data Service中使用API Key进行验证,主要代码来自于Ron Jacobs的这篇文章.
API Key作为一个参数在URL中传递, 在Rob Jacobs的WCFWebHttpLibrary.APIKeyAuthorization的方法string GetAPIKey(OperationContext operationContext)的代码如下:
1: public string GetAPIKey(OperationContext operationContext)
2: {
3: // Get the request message
4: var request = operationContext.RequestContext.RequestMessage;
5: // Get the HTTP Request
6: var requestProp =(HttpRequestMessageProperty)request.Properties[HttpRequestMessageProperty.Name];
7: // Get the query string
8: NameValueCollection queryParams =
9: HttpUtility.ParseQueryString(requestProp.QueryString);
10:
11: // Return the API key (if present, null if not)
12: string apiKey = queryParams[APIKEY];
13: // Is the API Key available in the querystring?
14: if (apiKey == null)
15: {
16: // Is the API Key available in the header?
17: apiKey = requestProp.Headers[APIKEY];
18: }
19: return apiKey;
20: }
WCF Data Service的OnStartProcessingRequest 方法在处理每个请求之前调用。对于批处理请求,将会为顶级批处理请求调用一次,然后为批处理中的每个操作调用一次。 我们在这个方法里可以实施自定义验证的相关逻辑:
1: protected override void OnStartProcessingRequest(ProcessRequestArgs args)
2: {
3: var queryParams = HttpUtility.ParseQueryString(args.OperationContext.AbsoluteRequestUri.Query);
4: string apiKey = queryParams[APIKEY];
5: if (apiKey == null)
6: {
7: apiKey = args.OperationContext.RequestHeaders[APIKEY];
8: }
9: if (CheckValidAPIKey(apiKey))
10: {
11: base.OnStartProcessingRequest(args);
12: }
13: else
14: {
15: throw new System.Web.Services.Protocols.SoapException();
16: }
17:
18: }
19:
客户端调用的时候,可以在SendingRequest事件添加到请求的Header里头:
1: class Program
2: {
3: static void Main(string[] args)
4: {
5: Uri serviceUri = new Uri("http://localhost/ProfilesDataService");
6:
7: ServiceReference.YUPEntities service = new ServiceReference.YUPEntities(serviceUri);
8: service.SendingRequest += new EventHandler<System.Data.Services.Client.SendingRequestEventArgs>
9:
10: (service_SendingRequest);
11:
12: var items = service.Execute<UserProfile>(new Uri(http://localhost/ProfilesDataService/GetUserProfile?username='testvip')).ToList();
13: foreach (UserProfile profile in items)
14: {
15: Console.WriteLine(profile.Title);
16: }
17: }
18:
19: static void service_SendingRequest(object sender,System.Data.Services.Client.SendingRequestEventArgs e)
20: {
21: // when using api in the header...
22: e.Request.Headers.Add("APIkey", "918704ec-4811-45b6-a169-16bae3df69a8");
23:
24: }
25:
26: }