2017-04-17 38 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