标签:style blog http color io os 使用 ar div
当你使用客户端发送请求 Web API 的时候,因为API 有验证,所以你的请求报文中必须有”Authorization“,那么就需要手动添加了!
HttpClient client = new HttpClient(); client.BaseAddress = new Uri("http://localhost:9014/"); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); //设置请求 Authorization: Basic eXN0Omp1bGk= Base64 加密的 (yst:juli) //System.Net.Http.Headers.AuthenticationHeaderValue authValue = new AuthenticationHeaderValue("Basic", "eXN0Omp1bGk="); //13e6ba0ee6f8559324efe6a3c51909f1 自定义加密的 System.Net.Http.Headers.AuthenticationHeaderValue authValue = new AuthenticationHeaderValue("ystJS", "13e6ba0ee6f8559324efe6a3c51909f1"); client.DefaultRequestHeaders.Authorization = authValue;
服务器端进行验证
public class ReqAuthorizeAttribute:System.Web.Http.AuthorizeAttribute { /// <summary> /// 进行验证 /// </summary> /// <param name="actionContext"></param> public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) { if (actionContext.Request.Headers.Authorization != null) { //获取请求的 认证信息(解密) 13e6ba0ee6f8559324efe6a3c51909f1 string authPa = (actionContext.Request.Headers.Authorization.Parameter).Decrypt(); string userInfo = "yst:juli"; //判断认证信息是否正确 if (string.Equals(authPa, userInfo)) { IsAuthorized(actionContext); } else { HandleUnauthorizedRequest(actionContext); } } else { HandleUnauthorizedRequest(actionContext); } } /// <summary> /// 验证不通过 返回401 /// </summary> /// <param name="actionContext"></param> protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext) { var challengeMsg = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Unauthorized); challengeMsg.Headers.Add("WWW-Authenticate", "Basic"); throw new System.Web.Http.HttpResponseException(challengeMsg); } }
关于ASP.NET Web API 客户端的请求报文中添加 Authorization
标签:style blog http color io os 使用 ar div
原文地址:http://www.cnblogs.com/yougmi/p/3978958.html