我正在尝试从 HttpRequest 消息中检索输入请求.HttpRequest 中显示内容类型和长度的内容.如何让 j



当前代码

if (!(context.Exception is exception))
HttpContent requestContent = context.Request.Content;
string jsonContent = requestContent.ReadAsStringAsync().Result;

Jsoncontent在这里返回

空值以及
context.request = context.HttpRequestMessage

在本地窗口中看到下面的输出

context.Request.Content.Headers {
Content-Length: 1458
Content-Type: application/json
}
Allow: {}
ContentDisposition: null
ContentEncoding: {}
ContentLanguage: {}
ContentLength: 1458
ContentLocation: null
ContentMD5: null
ContentRange: null
ContentType: { application/json }
Expires: null
LastModified: null
Results View: Expanding the Results View will enumerate the IEnumerable
context.Request.Content { System.Net.Http.StreamContent }
Headers: {
Content-Length: 1458
Content-Type: application/json
}

如何从标头中检索内容?

如果您希望内容类型和长度作为 json 字符串,您可以使用

JsonConvert.SerializeObject(Request.Content.Headers);
// Sample output 
// "[{"Key":"Content-Length","Value":["29"]},{"Key":"Content-Type","Value":["application/json"]}]"

requestContent.ReadAsStringAsync(( 返回空字符串,因为 body 只能读取一次。如果要使用 ReadAsStringAsync 读取正文,请从操作中删除参数(这将阻止默认模型绑定(。

// This will have Request.Content.ReadAsStringAsync as ""
public async Task<IHttpActionResult>  Post(MyModel model)

将其更改为

// This will have Request.Content.ReadAsStringAsync as json string
public async Task<IHttpActionResult>  Post()

博客对此进行了更详细的解释 https://blogs.msdn.microsoft.com/jmstall/2012/04/16/how-webapi-does-parameter-binding/

希望这个帮助

更新

如果您需要在异常过滤器中请求详细信息,则可以使用以下选项

选项 1(更容易,我建议使用它(

context.ActionContext.ActionArguments

var requestJson = $"RequestUrl: {context.Request.RequestUri} " +
$"ActionName: {context.ActionContext.ActionDescriptor.ActionName} " +
$"Arguments: {JsonConvert.SerializeObject(context.ActionContext.ActionArguments)}";
Debug.WriteLine(requestJson);

选项 2将 RequestStream 复制到 MemoryStream 并从位置 0 重新读取(从链接复制(

string request;
using (var memoryStream = new MemoryStream())
{
var requestStream = await context.Request.Content.ReadAsStreamAsync();
requestStream.Position = 0;
requestStream.CopyTo(memoryStream);
memoryStream.Position = 0;
using (StreamReader streamReader = new StreamReader(memoryStream))
{
request = streamReader.ReadToEnd();
}
}
Debug.WriteLine(request)

最新更新