我正在访问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;
}