我使用的是使用FromBody接受POST消息的REST代码。收到的参数是我需要使用的对象。现在,我需要检查标题中的授权。我想通过将参数从对象切换到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对象?
答案 0 :(得分:2)
只需使用以前的签名方法来计算数据。您可以像这样直接访问标题值
Request.Headers.Authorization.Parameter
Request
是ApiController
为每个请求提供的对象。
答案 1 :(得分:2)
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。
你应该调查