简体   繁体   English

我正在尝试从HttpRequest消息中检索输入请求。 HttpRequest中的内容显示了内容类型和长度。 如何获取json?

[英]I am trying to retrieve input request from HttpRequest message. Content in HttpRequest showing content type and length. How do I get json out?

Current code 当前代码

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

Jsoncontent returns null here as well as Jsoncontent在这里以及返回null

context.request = context.HttpRequestMessage

Seeing below output in local window 在本地窗口中看到以下输出

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
}

How do I retrieve content from header? 如何从标题中检索内容?

If you want content-type and length as json string, you can use 如果要将content-type和length作为json字符串,则可以使用

 JsonConvert.SerializeObject(Request.Content.Headers);

 // Sample output 
 // "[{\"Key\":\"Content-Length\",\"Value\":[\"29\"]},{\"Key\":\"Content-Type\",\"Value\":[\"application/json\"]}]"

requestContent.ReadAsStringAsync() return empty string because body can only be read once. requestContent.ReadAsStringAsync()返回空字符串,因为正文只能读取一次。 If you want to read body using ReadAsStringAsync then remove parameter from actions (this will prevent default model binding). 如果要使用ReadAsStringAsync读取正文,请从操作中删除参数(这将防止默认模型绑定)。

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

Change it to 更改为

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

Blog explains this in more detail https://blogs.msdn.microsoft.com/jmstall/2012/04/16/how-webapi-does-parameter-binding/ 博客对此进行了更详细的说明https://blogs.msdn.microsoft.com/jmstall/2012/04/16/how-webapi-does-parameter-binding/

Hope this help 希望这个帮助

Update 更新资料

If you need request details in exception filter then you can use following options 如果您需要异常过滤器中的请求详细信息,则可以使用以下选项

Options 1 (easier and I would advise to use this) 选项1 (更简单,我建议您使用此选项)

Use 采用

       context.ActionContext.ActionArguments

Example

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

        Debug.WriteLine(requestJson);

Options 2 copy RequestStream to MemoryStream and reread from position 0 (copied from link ) 选项2将RequestStream复制到MemoryStream并从位置0重新读取(从link复制)

        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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何获取httprequest内容以在C#中的localhost上显示? - How do I get httprequest content to display on localhost in c#? 如何在 c# 中将 Google.Cloud.Tasks.V2 HttpRequest 的 Content-Type 设置为“application/json”? - How to set the Content-Type to "application/json" for Google.Cloud.Tasks.V2 HttpRequest in c#? 如何在“天蓝色函数”上模拟 HttpRequest - How do I mock the HttpRequest on an "azure function" 如何从 System.Web.HttpRequest 获取协议版本? - How do I get protocol version from System.Web.HttpRequest? 如何更改或删除HttpModule中的HttpRequest输入参数 - How can I change or remove HttpRequest input arguments in a HttpModule 如何在GET请求中包含内容? - How do I include content with a GET request? 如何将HttpRequest复制到另一个Web服务? - How do I copy a HttpRequest to another web service? 如何将一些自定义数据与当前的HttpRequest相关联? - How do I associate some custom data with current HttpRequest? 如何使用C#HttpRequest获取ASP应用程序变量? - How can I get ASP Application variables with C# HttpRequest? 如何自定义 HTTP 错误 411。请求必须分块或具有内容长度。 在 IIS 上 - How to custom HTTP Error 411. The request must be chunked or have a content length. on IIS
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM