New Uri (URL), client. DefaultRequestHeaders.Accept.Clear (); client. DEFAULTREQUESTHEADERS.ACCEPT.ADD (new mediatypewithqualityheadervalue ("application/ JSON"), client. Defaultrequestheaders.add ("x-apikey","00000") ;
Writing Apikeyhandler
Public classApikeyhandler:delegatinghandler { Public stringKey {Get;Set; } PublicApikeyhandler (stringkey,httpconfiguration httpconfiguration) { This. Key =key; Innerhandler=NewHttpcontrollerdispatcher (httpconfiguration); } protected OverrideTaskSendAsync (httprequestmessage request, CancellationToken CancellationToken) {if(!Validatekey (Request)) { varResponse =Newhttpresponsemessage (Httpstatuscode.forbidden); varTSC =NewTaskcompletionsource(); Tsc. Setresult (response); returnTSC. Task; } return Base. SendAsync (Request, CancellationToken); } Private BOOLValidatekey (Httprequestmessage message) {IEnumerable<string> apikeyheadervalues =NULL; if(Message. Headers.trygetvalues ("X-apikey", outapikeyheadervalues)) { varApikeyheadervalue =Apikeyheadervalues.first (); return(Apikeyheadervalue = = This. Key)//... your authentication logic here ... /*var username = (Apikeyheadervalue = = "00000"?) "Maarten": "OtherUser"); var usernameclaim = new Claim (claimtypes.name, username); var identity = new Claimsidentity (new[] {usernameclaim}, "ApiKey"); var principal = new ClaimsPrincipal (identity); Thread.CurrentPrincipal = Principal; */ } /*var query = message. Requesturi.parsequerystring (); string key = query["Key"]; return (key = = this. Key); */ }
Configure to a specific route up
config. Routes.maphttproute (name: " default Api , Routetemplate: " api/{controller}/{id} " new {ID = routeparameter.optional}, constraints: null new Apik Eyhandler ( " 12345 "
Using Delegatinghandler to implement API key validation for Web APIs