When you use the client to send the request Web API, because the API is verified, so your request message must have "Authorization", then you need to manually add!
HttpClient client =NewHttpClient (); client. BaseAddress=NewUri ("http://localhost:9014/"); client. DEFAULTREQUESTHEADERS.ACCEPT.ADD (NewMediatypewithqualityheadervalue ("Application/json"));//Set Request Authorization:basic exn0omp1bgk= Base64 Encrypted (Yst:juli)//System.Net.Http.Headers.AuthenticationHeaderValue authvalue = new Authenticationheadervalue ("Basic", " Exn0omp1bgk= ");//13E6BA0EE6F8559324EFE6A3C51909F1 the custom encryptedSystem.Net.Http.Headers.AuthenticationHeaderValue Authvalue =NewAuthenticationheadervalue ("Ystjs","13e6ba0ee6f8559324efe6a3c51909f1"); client. Defaultrequestheaders.authorization= Authvalue;
Server-side validation
Public classreqauthorizeattribute:system.web.http.authorizeattribute{/// <summary> ///to verify/// </summary> /// <param name= "Actioncontext" ></param> Public Override voidonauthorization (System.Web.Http.Controllers.HttpActionContext actioncontext) {if(ActionContext.Request.Headers.Authorization! =NULL) { //Gets the requested authentication information (decryption) 13E6BA0EE6F8559324EFE6A3C51909F1 stringAUTHPA =(ActionContext.Request.Headers.Authorization.Parameter). Decrypt (); stringUserInfo ="Yst:juli"; //Determine if the authentication information is correct if(string. Equals (AUTHPA, UserInfo)) {isauthorized (actioncontext); } Else{handleunauthorizedrequest (actioncontext); } } Else{handleunauthorizedrequest (actioncontext); } } /// <summary> ///validation does not pass return 401/// </summary> /// <param name= "Actioncontext" ></param> protected Override voidhandleunauthorizedrequest (System.Web.Http.Controllers.HttpActionContext actioncontext) {varChallengemsg =NewSystem.Net.Http.HttpResponseMessage (System.Net.HttpStatusCode.Unauthorized); CHALLENGEMSG.HEADERS.ADD ("www-authenticate","Basic"); Throw NewSystem.Web.Http.HttpResponseException (challengemsg); }}
View Code
Adding Authorization to request messages about the ASP Web API client