2012-05-20 8 views
5

Ich habe ein ActionFilterAttribute für meine Web-API erstellt, um Leute zu autorisieren. GettingAccessToken von RequestUri ist in Ordnung, aber ich möchte es in Formulardaten senden. Beim Lesen von Request.Content in der onActionExecuting-Methode von ActionFilterAttribute hat der Server immer ein leeres Ergebnis. Wie kann ich dieses Problem lösen? Der Code ist so ähnlich wie unten:Lesen von Formulardaten 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

Haben Sie die Antwort? Ich habe dasselbe Problem – Ahmadreza

Antwort

3

Es ist liegt daran, dass der HttpContent durch den Formatierer vor Action gelesen. Die Web-API erlaubt nur das einmalige Lesen von Inhalten. Sie können es also nicht mehr lesen.

Hier ist eine mögliche Lösung für Sie. Zuerst machen Sie Ihren Aktionsparameter als FormDataCollection:

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

Dann bekommen sie in Action von Code:

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); 
    } 
Verwandte Themen