2017-04-17 37 views
0

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

回答

0

我找到了答案的职位之一。这样的流只能读取一次,因此我将它复制到Memory Stream中。

using (var stream = new MemoryStream()) 
     { 
      context.Request.InputStream.Seek(0, SeekOrigin.Begin); 
      context.Request.InputStream.CopyTo(stream); 
      string requestBody = Encoding.UTF8.GetString(stream.ToArray()); 
      if(requestBody!=string.Empty) 
      { 
       JObject inputReqObj = JObject.Parse(requestBody); 
       UserID = (string)inputReqObj["eUserID"]; 
      } 
     }   

现在,我仍然可以从我的customAuthorize类中读取上面给出的问题。我必须做的唯一改变是在global.asax文件中。在下面的文章中找到了这个答案,稍微调整了一下以适应我的要求。 How to get hold of Content that is already read