6

我为我的 web api 创建了一个 ActionFilterAttribute 来授权人们。通过 RequestUri 获取 accessToken 是可以的,但是我想以表单数据的形式发送它。在读取 ActionFilterAttribute 的 onActionExecuting 方法中的 Request.Content 时,服务器总是有一个空结果。我怎么解决这个问题?代码如下:

    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);
    }
}
4

1 回答 1

8

这是因为 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);
    }
于 2012-09-23T10:26:21.030 回答