问题描述
我为我的Web api创建了一个ActionFilterAttribute来授权人员.通过RequestUri获取accessToken是可以的,但是我想以表单数据发送它.在用ActionFilterAttribute的onActionExecuting方法读取Request.Content时,服务器始终有一个空结果.我怎么解决这个问题?代码如下:
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 Request.Content in onActionExecuting method of ActionFilterAttribute, server always has an empty result. How can i solve this problem? The code is as like as below:
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);
}
}
推荐答案
这是因为格式化程序在ActionFilter之前已读取HttpContent. Web API只允许读取一次内容.因此,您将无法再次阅读.
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.
这是您的可能解决方案.首先,将操作参数设置为FormDataCollection:
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>();
// ...
然后,通过代码在ActionFilter中获取它:
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);
}
这篇关于在ActionFilterAttribute中读取表单数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!