我正在訪問WebAPI中global.asax文件的application_beginrequest方法中的POST請求。然後,一旦我從請求中獲取UserID,然後我再次嘗試從HttpActionContext方法獲取相同的請求,並試圖customauthorize用戶,但是一旦我在global.asax文件中獲取數據,參數將不再可用CustomAuthorization類。不知道是否爲什麼會發生這種情況,以及這是否是有意識的行爲。請有人解釋發生了什麼事。請在下面找到我的代碼。一次在global.asax中訪問的POST請求無法在CustomAuthorization類中訪問 - WebAPI
的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;
}