我为我的 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);
}
}