How do I get the raw request body from the Request.Content object using .net 4 api endpoint

后端 未结 4 1475
北海茫月
北海茫月 2020-12-09 15:02

I\'m trying to capture the raw request data for accountability and want to pull the request body content out of the Request object.

I\'ve seen suggestions doing a Re

4条回答
  •  醉酒成梦
    2020-12-09 15:42

    If you need to both get the raw content from the request, but also need to use a bound model version of it in the controller, you will likely get this exception.

    NotSupportedException: Specified method is not supported. 
    

    For example, your controller might look like this, leaving you wondering why the solution above doesn't work for you:

    public async Task Index(WebhookRequest request)
    {
        using var reader = new StreamReader(HttpContext.Request.Body);
    
        // this won't fix your string empty problems
        // because exception will be thrown
        reader.BaseStream.Seek(0, SeekOrigin.Begin); 
        var body = await reader.ReadToEndAsync();
    
        // Do stuff
    }
    

    You'll need to take your model binding out of the method parameters, and manually bind yourself:

    public async Task Index()
    {
        using var reader = new StreamReader(HttpContext.Request.Body);
    
        // You shouldn't need this line anymore.
        // reader.BaseStream.Seek(0, SeekOrigin.Begin);
    
        // You now have the body string raw
        var body = await reader.ReadToEndAsync();
    
        // As well as a bound model
        var request = JsonConvert.DeserializeObject(body);
    }
    

    It's easy to forget this, and I've solved this issue before in the past, but just now had to relearn the solution. Hopefully my answer here will be a good reminder for myself...

提交回复
热议问题