關於ASP.NET Web API 用戶端的請求報文中添加 Authorization

來源:互聯網
上載者:User

標籤: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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.