拦截Web API请求并更改正文/内容 [英] Intercept Web API Request and change body/content
问题描述
您好,
我正在Web API应用程序中试验OWIN中间件,我希望拦截管道中的请求并解码之前的请求正文请求到达API Controller / Action。
我已经采用了json字符串,base 64编码了它作为此测试的一部分。我能够拦截请求,读取正文,解码它以获取原始字符串,但我无法使用新数据更新请求正文。以下是代码段:
Hello,
I am experimenting with OWIN middleware in an Web API application and I wish to intercept the request in the pipeline and decode the request body in flight before the request gets to the API Controller/Action.
I have taken a json string and base 64 encoded it as part of this test. I am able to intercept the request, read the body text, decode it as to get the original string but I am unable to update the request body with the new data. Here is a code snippet:
public override async Task Invoke(IOwinContext context)
{
if (context.Request.ContentType.Equals("text/plain"))
{
string body = new StreamReader(context.Request.Body).ReadToEnd();
byte[] data = Convert.FromBase64String(body);
string decodedString = Encoding.UTF8.GetString(data);
context.Request.ContentType = "application/json";
context.Request.Body = new MemoryStream(Encoding.UTF8.GetBytes(decodedString));
}
await Next.Invoke(context);
}
此代码执行没有问题,我可以看到具有正确数据的已解码字符串值。踢球者是当请求移动到控制器/动作时,正文是旧数据/编码字符串的主体。
有没有人试图拦截api通过owin请求并将其替换为最初发布的内容以外的其他内容?
示例控制器/动作剪切用于从请求正文中提取值:
This code executes without issue and I can see decoded string value having the correct data. The kicker is that when the request moves on to the controller / action, the body is that of the old data / encoded string.
Has anyone tried to intercept the api request via owin and replace it with something other than what was originally posted?
Sample controller / action snipped used to pull the value from the request body:
// POST api/values
public void Post([FromBody]string value)
{
var req = Request;
var x = value;
var y = x;
}
提前致谢!
CC
-
Thanks in advance!
CC
-
推荐答案
以下链接将帮助您:
http://stackoverflow.com/questions/27036448/how-to-intercept-404-using-owin-middleware [ ^ ]
https:/ /maximelabelle.wordpress.com/2014/10/08/capturing-rest-api-calls-with-an-owin-middleware/ [ ^ ]
这篇关于拦截Web API请求并更改正文/内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!