gpt4 book ai didi

c# - 在 ActionFilterAttribute 中读取表单数据

转载 作者:太空狗 更新时间:2023-10-29 23:16:52 26 4
gpt4 key购买 nike

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

最佳答案

这是因为HttpContent 在ActionFilter 之前已经被formatter 读取过了。 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);
}

关于c# - 在 ActionFilterAttribute 中读取表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10673649/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com