c# - ASP.Net WebApi 不通过内容返回表单数据

标签 c# asp.net asp.net-web-api

我不知道这是否是一个错误,但我无法在服务器端获取原始请求。

考虑以下 Controller 方法:

[AllowAnonymous]
[Route("api/sayHello")]
[HttpPost]
public string SayHello([FromBody] string userName)
{
    return $"Hello, {userName}.";
}

我通过 cUrl 调用它:

curl -X POST 'https://localhost:809/api/sayHello' --insecure -d "=userName"

它工作正常。 enter image description here

现在我正在尝试添加一些日志记录。我添加了一个执行以下操作的全局过滤器:

public async Task LogFilterAction(HttpActionContext context)
{
    if (context == null)
        throw new ArgumentNullException(nameof(context));
    LogFilterAction(context.ActionDescriptor?.ControllerDescriptor?.ControllerType,
        context.ActionDescriptor?.ActionName,
        context.Request?.RequestUri,
        await GetDataAsString(context.Request?.Content),
        context.Response?.StatusCode
    );
}

private static async Task<string> GetDataAsString(HttpContent content)
{
    if (content == null)
        return null;
    var contentBytes = await content.ReadAsByteArrayAsync();
    return Encoding.UTF8.GetString(contentBytes);
}

但这就是问题所在:由于未知原因,contentBytes 始终是一个空数组。我看到它的实际长度是 9(它是 =userName 字符串的长度)

enter image description here

甚至

enter image description here

如您所见,ASP.Net 已成功请求参数,但是,它没有以原始方式返回。 Stream有position=0,contentConsumed=false,其他都正常。但是我无法读取传递给 Controller ​​的数据。

这里有什么问题吗?

最佳答案

ASP.NET Web API 只读取一次内容,因此在您访问内容流时,它已经被读取并且流位于其末尾。再次尝试读取内容将不会返回任何内容。

但是,在一个小示例中,我能够重置流并再次读取它:

private async Task<string> GetDataAsString(HttpContent content)
{
    if (content == null)
        return null;
    using (var str = await content.ReadAsStreamAsync())
    {
        if (str.CanSeek)
            str.Seek(0, System.IO.SeekOrigin.Begin);
        using (var rdr = new StreamReader(str))
        {
            return rdr.ReadToEnd();
        }
    }
}

但是,为了避免副作用,您可能要考虑使用 ActionArguments ActionContext 的属性。您可以使用此属性来检索传递给记录操作的值。这不会干扰 ASP.NET Web API 的内部管道。

关于c# - ASP.Net WebApi 不通过内容返回表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47680130/

相关文章:

c# - 计算每行文本文件的制表符数

c# - IndexOf() 方法始终返回 -1

rest - 如果客户端向不存在的 Web API 资源发出 DELETE 请求,应该返回什么

asp.net - 添加标签来讨论 Entity Framework 中的多对多关系

c# - 如何保存拖动项目的位置

c# - ASP.NET Web API 的 JWT 身份验证

c# - 使用 Simple Injector 将依赖项注入(inject) OWIN 中间件和每个 Web 请求

c# - 仅在自上次使用后 X 秒后执行方法

c# - 我怎样才能在没有重复行的情况下编写代码?

c# - 无法对空引用执行运行时绑定(bind)。 ViewBag.Title 为空