Reading Form Data in ActionFilterAttribute

后端 未结 1 1613
我在风中等你
我在风中等你 2021-02-09 17:06

I created an ActionFilterAttribute for my web api in order to authorize people. Getting accessToken by RequestUri is okay, however i want to send it in form data. While reading

相关标签:
1条回答
  • 2021-02-09 17:34

    It's is because the HttpContent has been read by the formatter before ActionFilter. Web API only allows reading content once. So you are unable to read it again.

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

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

    Then, get it in 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);
        }
    
    0 讨论(0)
提交回复
热议问题