標籤: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); }}
View Code
關於ASP.NET Web API 用戶端的請求報文中添加 Authorization