gpt4 book ai didi

c# - 将 POST FromBody 转换为 HttpRequestMessage - 需要反序列化请求正文

转载 作者:行者123 更新时间:2023-11-30 20:29:11 28 4
gpt4 key购买 nike

我有工作的 REST 代码,可以使用 FromBody 接受 POST 消息。收到的参数是我需要处理的对象。现在,我需要检查 header 中的授权。我想通过将参数从对象切换到 HttpRequestMessage 来解决这个问题。当然,现在消息的内容必须转换为原始对象,我很难理解。

这是原始方法:

    [HttpPost]
public IHttpActionResult Post([FromBody] CardStatusRoot cardStatus)
{
try
{
if (cardStatus == null)
{
return BadRequest("Card data not provided");
}
if (cardStatus.Data.TransactionType.ToLower() == "card")
{
//... Process;
}
}
catch (Exception ex)
{
try
{
// Log the failure to fund the card
}
catch { }

return InternalServerError();
}
return Ok();
}

新代码,使用 HttpRequestMessage:

    [HttpPost]
public IHttpActionResult Post(HttpRequestMessage request)
{
// Get the authentication from the header
var encoding = Encoding.GetEncoding("UTF-8");
var authValue = encoding.GetString(Convert.FromBase64String(request.Headers.Authorization.Parameter));
var validAuthorization = ConfigurationManager.AppSettings["ValidKey"];

if (authValue != validAuthorization)
{
return BadRequest("Not Authorized");
}

// This does NOT compile - Need help converting request.Content to a CardStatusRoot object
CardStatusRoot cardStatus = (CardStatusRoot)request.Content.ReadAsStringAsync().Result;

... Same as first method
}

如何将请求的内容转换为 CardStatusRoot 对象?

最佳答案

ApiController 可以通过 Request 属性访问当前请求。

[HttpPost]
public IHttpActionResult Post([FromBody] CardStatusRoot cardStatus) {
try {
HttpRequestMessage request = this.Request;
if (cardStatus == null) {
return BadRequest("Card data not provided");
}
if (cardStatus.Data.TransactionType.ToLower() == "card") {
//... Process;
}
} catch (Exception ex) {
try {
// Log the failure to fund the card
}
catch { }

return InternalServerError();
}
return Ok();
}

也就是说,这个问题感觉更像是一个 XY problem .

你应该调查一下

Authentication Filters in ASP.NET Web API 2

Global Error Handling in ASP.NET Web API 2

关于c# - 将 POST FromBody 转换为 HttpRequestMessage - 需要反序列化请求正文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46472576/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com