2012-05-20 57 views
5

我爲我的web api創建了ActionFilterAttribute以授權人員。通過RequestUri獲取accessToken是可以的,但是我想通過表單數據發送它。在閱讀ActionFilterAttribute的onActionExecuting方法中的Request.Content時,服務器總是有一個空的結果。我怎麼解決這個問題?代碼如下所示:閱讀表單數據in ActionFilterAttribute

public class RequireAuthorization : ActionFilterAttribute 
{ 

    public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) 
    { 
     actionContext.Request.Content.ReadAsStringAsync().ContinueWith((t) => 
     { 
      try 
      { 
       //query will result in empty string 
       string query = t.Result; 

       string UserID = HttpUtility.ParseQueryString(query).Get("UserID"); 
       string accessToken = HttpUtility.ParseQueryString(query).Get("AccessToken"); 

       UserRepository repository = new UserRepository(); 
       repository.IsTokenValid(Convert.ToInt32(UserID), accessToken); 
      } 
      catch (Exception ex) 
      { 
       var response = new HttpResponseMessage 
       { 
        Content = 
         new StringContent("This token is not valid, please refresh token or obtain valid token!"), 
        StatusCode = HttpStatusCode.Unauthorized 
       }; 

       throw new HttpResponseException(response); 
      } 
     }); 


     base.OnActionExecuting(actionContext); 
    } 
} 
+0

你找到答案嗎?我有同樣的問題 – Ahmadreza

回答

3

這是因爲HttpContent已被格式化程序在ActionFilter之前讀取。 Web API只允許閱讀一次內容。所以你不能再讀一遍。

以下是您可能的解決方案。首先,讓你的操作參數作爲FormDataCollection:

[RequireAuthorization] 
    public HttpResponseMessage PostTodo(FormDataCollection formData) 
    { 
     Todo todo = formData.ReadAs<Todo>(); 
     // ... 

然後,讓它在ActionFilter由代碼:

public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext) 
    { 
     var formData = actionContext.ActionArguments["formData"] as FormDataCollection; 
     if (formData != null) 
     { 
      var userID = formData.Get("UserID"); 
      var accessToken = formData.Get("AccessToken"); 
      // authorize 
     } 

     base.OnActionExecuting(actionContext); 
    }