I am accessing the POST request in the application_beginrequest method of the global.asax file in WebAPI. And once I get the UserID there from the request, I then tried to get the same request again from the HttpActionContext method and tried to customauthorize the user but once I get the data in global.asax file, the parameters are no more available in the CustomAuthorization class. Not sure if why this is happening and if this is the intented behaviour. could somebody please explain what is happening. Please find my code below.
Global.asax
protected void Application_BeginRequest(Object source, EventArgs e)
{
var userID = GetUserID(HttpContext.Current);
try
{
CustomAuthorizeAttribute customObj= new CustomAuthorizeAttribute();
if (!customObj.AuthorizeRequest(userID))
{
throw new Exception();
}
}
catch (Exception ex)
{
throw ex;
}
}
private string GetUserID(HttpContext context)
{
string UserID = string.Empty;
using (var stream= new StreamReader(context.Request.InputStream))
{
string inputData = stream.ReadToEnd();
//code to parse the data and get the userID value.
}
return userID;
}
CustomAuthorizeAttribute.cs
public override void OnAuthorization(System.Web.Http.Controllers.HttpActionContext actionContext)
{
userID = GetUser(actionContext);
if (CustomAuthorize(userID))
{
return;
}
}
private string GetUser(System.Web.Http.Controllers.HttpActionContext actionContext)
{
var username = string.Empty;
var request = actionContext.Request.Content.ReadAsStringAsync().Result;
if ((request != null) && (request != string.Empty))
{
JObject Obj = JObject.Parse(request);
if (Obj != null)
username = (string)Obj ["userID"];
}
return username;
}