我有可用的REST代码,可以使用FromBody接受POST消息。收到的参数是我需要使用的对象。现在,我需要检查标题中的授权。我认为可以通过将参数从对象切换到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