当前,我正在将加密的请求发送到asp.net核心控制器。以下是请求正文结构:
{
"body": "pEbXVvl1ue95eGQywK/q80cGHjYk+2VNPYEgnRgU+vI="
}
在我实现过滤器IActionFilter
之前,我在OnActionExecuting(ActionExecutingContext context)
中解密了上述请求正文(正文密钥)
解密后,我得到了解密的请求主体,如下所示:
{
"Urno":"URN123456"
}
解密后,我想将解密的请求(上面"Urno":"URN123456"
所述)主体传递给控制器
我尝试将字符串转换为字节,而不是将其传递给Request.body
,但没有成功:
public void OnActionExecuting(ActionExecutingContext context)
{
var request = context.HttpContext.Request;
request.EnableRewind();
request.Body.Position = 0;
using (var reader = new StreamReader(request.Body))
{
var bodyString = reader.ReadToEnd(); //{ "body": "pEbXVvl1ue95eGQywK/q80cGHjYk+2VNPYEgnRgU+vI="}
if (bodyString != "")
{
var data = JObject.Parse(bodyString);
var key = data.GetValue("body");
var keybytes = Encoding.UTF8.GetBytes("808080808080808011");
var iv = Encoding.UTF8.GetBytes("8080808080808080111");
var encrypted = Convert.FromBase64String(key.ToString());
var decriptedFromJavascript = DecryptStringFromBytes(encrypted, keybytes, iv); //{ "Urno":"URN123456"}
byte[] bytes = Encoding.ASCII.GetBytes(decriptedFromJavascript);
request.Body = new MemoryStream(bytes); // here i am trying to change request body
}
}
}
// controller
[HttpPost("[action]")]
public async Task<string> GetInvestorUrno(Urnoinvestor InfoReq){
}
// class
public class Urnoinvestor
{
public string Urno{ get; set; }
}
我想更改请求正文并将解密的请求传递给控制器
答案 0 :(得分:1)
对于您的情况,IActionFilter
不起作用。查看此图片:
Model binding
在ActionFilter
之前运行,这意味着无论您对主体进行什么更改,都不会更改模型。您需要在进行模型绑定之前尝试使用过滤器,例如Resource filter
。
更改为Resource filter
public class RequestBodyFilter : IResourceFilter
{
public void OnResourceExecuted(ResourceExecutedContext context)
{
//throw new NotImplementedException();
}
public void OnResourceExecuting(ResourceExecutingContext context)
{
var request = context.HttpContext.Request;
request.EnableRewind();
request.Body.Position = 0;
using (var reader = new StreamReader(request.Body))
{
var decriptedFromJavascript = "{ \"Urno\":\"URN123456\"}"; //{ "Urno":"URN123456"}
byte[] bytes = Encoding.ASCII.GetBytes(decriptedFromJavascript);
request.Body = new MemoryStream(bytes); // here i am trying to change request body
}
}
}
由于您是从身体绑定的,因此您需要使用[FromBody]
指定动作,作为@Tony Abrams的建议。
[HttpPost("[action]")]
[TypeFilter(typeof(RequestBodyFilter))]
public async Task<string> GetInvestorUrno([FromBody]Urnoinvestor InfoReq)
{
return InfoReq.Urno;
}
答案 1 :(得分:0)
您必须设置request.Body.Position = 0。否则,您将获得一个空的正文异常。
request.Body.Position = 0;
request.Body = new MemoryStream(bytes);
答案 2 :(得分:-1)
您没有将参数标记为from正文,因此它不会从请求正文中加载数据。相反,它期望它在URI中。
尝试以下方法:
[HttpPost("[action]")]
public async Task<string> GetInvestorUrno([FromBody]Urnoinvestor InfoReq){
}