.net 如何在授权期间解密服务器上的负载并Map到Web API中的模型

w8f9ii69  于 2023-02-10  发布在  .NET
关注(0)|答案(1)|浏览(111)

我一直在尝试遵循this答案,尝试在将模型Map到控制器之前,在授权过程中解密加密的有效负载。
从客户端只有负载将被加密,在服务器端我试图解密。事情是整个Response.content不能解密,因为只有负载需要解密。

在内容内部,我们接收Result的有效载荷,当我尝试更改时,它显示为只读,我看不到任何其他选项。在上图中,结果尚未加密,我正在测试是否可以更改。
我用另一种方法完成了它,我将把整个加密字符串传递给控制器,然后解密它并Map到控制器内部的模型,如下所示:

[Route("api/xxxxxx")]
        [HttpPost]
        public HttpResponseMessage PostTest(string encryptedValue)
        {
            //creating an instance of class
            HttpResponseMessage response = new HttpResponseMessage();
            
            try
            {
               string decryptJson = AES.DecryptString(encryptedValue);
               Model list = JsonConvert.DeserializeObject<Model>(decryptJson);
               
               //rest of the operation

            }
            //to catch exceptions if any
            catch (Exception ex)
            {
                output.Success = false;
                output.Message = Literals.GetErrorMessage(ex.Message);
            }
            //creating response
            response = Request.CreateResponse(HttpStatusCode.OK, JObject.FromObject(output));

            //returning response
            return response;
        }

这是工作的预期,但我尝试,如果在所有有可能这样做的授权,而不是这样做的每个控制器单独。
任何建议都很感激。

vwoqyblh

vwoqyblh1#

使用new StringContent()将解密后的字符串添加到响应中。

public class LogAttribute : AuthorizeAttribute
    {

        public override void OnAuthorization(HttpActionContext actionContext)
        {
            try
            {
               var resoponseContent = actionContext.Request.Content.ReadAsStringAsync();

                var result = resoponseContent.Result;

                var decryptedString = AESEncryptDecrypt.DecryptStringAES(result);

                actionContext.Request.Content = new StringContent(decryptedString, Encoding.UTF8, "application/json");

                var checkingDecryptedResponseContent = actionContext.Request.Content.ReadAsStringAsync();

            }
            catch (Exception ex)
            {
            }
        }
    }

更新新内容后,模型将自动Map到控制器。

[LogAttribute]
        [Route("api/xxxxxx")]
        [HttpPost]
        public HttpResponseMessage PostTest(Model data)
        {
            //creating an instance of class
            HttpResponseMessage response = new HttpResponseMessage();
            
            try
            {
               
               //rest of the operation

            }
            //to catch exceptions if any
            catch (Exception ex)
            {
                output.Success = false;
                output.Message = Literals.GetErrorMessage(ex.Message);
            }
            //creating response
            response = Request.CreateResponse(HttpStatusCode.OK, JObject.FromObject(output));

            //returning response
            return response;
        }

相关问题