Reading form data in ActionFilterAttribute

I created an ActionFilterAttribute for my web api to allow people. Getting the accessToken through RequestUri is fine, however I want to send it to the form data. When reading Request.Content in the onActionExecuting ActionFilterAttribute method, the server always has an empty result. How can I solve this problem? The code looks like this:

    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);
    }
}
+5
source share
1 answer

This is because HttpContent was read by formatting before the ActionFilter. The web API allows you to read only once. Therefore, you cannot read it again.

Here is a possible solution for you. First, make your action parameter as FormDataCollection:

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

Then enter it in the ActionFilter by 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);
    }
+3

All Articles