ASP.NET Core modify/substitute request body

前端 未结 1 1299
一个人的身影
一个人的身影 2020-12-10 13:30

I want to do a substitution on HttpContext.Request.Body.

I\'ve tried to do it inside a middleware:

public async Task Invoke(HttpContext co         


        
相关标签:
1条回答
  • 2020-12-10 14:13

    Take the request body, read its content, make whatever changes are necessary if at all, then create a new stream to pass down the pipeline. Once accessed, the request stream has to be replaced.

    public async Task Invoke(HttpContext context) {
        var request = context.Request;
        if (request.Path.Value.Contains("DataSourceResult")) {
            //get the request body and put it back for the downstream items to read
            var stream = request.Body;// currently holds the original stream                    
            var originalContent = new StreamReader(stream).ReadToEnd();
            var notModified = true;
            try {
                var dataSource = JsonConvert.DeserializeObject<DataSourceRequest>(originalContent);
                if (dataSource != null && dataSource.Take > 2000) {
                    dataSource.Take = 2000;
                    var json = JsonConvert.SerializeObject(dataSource);
                    //replace request stream to downstream handlers
                    var requestContent = new StringContent(json, Encoding.UTF8, "application/json");
                    stream = await requestContent.ReadAsStreamAsync();//modified stream
                    notModified = false;
                }
            } catch {
                //No-op or log error
            }
            if (notModified) {
                //put original data back for the downstream to read
                var requestData = Encoding.UTF8.GetBytes(originalContent);
                stream = new MemoryStream(requestData);
            }
    
            request.Body = stream;
        }
        await _next.Invoke(context);
    }
    
    0 讨论(0)
提交回复
热议问题