protected override void HandleUnauthorizedRequest(System.Web.Http.Controllers.HttpActionContext actionContext) { if (!HttpContext.Current.User.Identity.IsAuthenticated) { base.HandleUnauthorizedRequest(actionContext); // { // "Message": "Authorization has been denied for this request." // } string tk = string.Empty; var re = actionContext.Request; var headers = re.Headers; string meth = re.Method.ToString(); if (headers.Contains("Authorization")) { tk = headers.GetValues("Authorization").FirstOrDefault(); } if (tk.StartsWith("Bearer ")) { tk = tk.Replace("Bearer ", ""); } string stUri = actionContext.Request.RequestUri.AbsolutePath; VarsSubsFunc.AddCardexTokens(stUri, meth, (int)System.Net.HttpStatusCode.Unauthorized, nameof(System.Net.HttpStatusCode.Unauthorized), VarsSubsFunc.GetIpAddress().Trim(), tk); var resp = new { Message = "Authorization has been denied for this request." }; string yourJson = JsonConvert.SerializeObject(resp); actionContext.Response = new System.Net.Http.HttpResponseMessage() { StatusCode = System.Net.HttpStatusCode.Unauthorized, Content = new System.Net.Http.StringContent(yourJson, Encoding.UTF8, "application/json") }; } else { string tk = string.Empty; var re = actionContext.Request; var headers = re.Headers; string meth = re.Method.ToString(); if (headers.Contains("Authorization")) { tk = headers.GetValues("Authorization").FirstOrDefault(); } if (tk.StartsWith("Bearer ")) { tk = tk.Replace("Bearer ", ""); } string stUri = actionContext.Request.RequestUri.AbsolutePath; VarsSubsFunc.AddCardexTokens(stUri, meth, (int)System.Net.HttpStatusCode.Forbidden, nameof(System.Net.HttpStatusCode.Forbidden), VarsSubsFunc.GetIpAddress().Trim(), tk); actionContext.Response = new System.Net.Http.HttpResponseMessage(System.Net.HttpStatusCode.Forbidden); } }
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext) { if (!base.IsAuthorized(actionContext)) { HandleUnauthorizedRequest(actionContext); } else { string tk = string.Empty; var re = actionContext.Request; var headers = re.Headers; string meth = re.Method.ToString(); if (headers.Contains("Authorization")) { tk = headers.GetValues("Authorization").FirstOrDefault(); } if (tk.StartsWith("Bearer ")) { tk = tk.Replace("Bearer ", ""); } string stUri = actionContext.Request.RequestUri.AbsolutePath; VarsSubsFunc.AddCardexTokens(stUri, meth, (int)System.Net.HttpStatusCode.Accepted, nameof(System.Net.HttpStatusCode.Accepted), VarsSubsFunc.GetIpAddress().Trim(), tk); } }