关于ASP.NET Web API 客户端的请求报文中添加 Authorization

当你使用客户端发送请求 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;       

 

服务器端进行验证

关于ASP.NET Web API 客户端的请求报文中添加 Authorization
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

上一篇:Windows下配置使用 MemCached


下一篇:CUDA 6.5 && VS2013 && Win7:创建CUDA项目