[英]How can I bind simple type coming from body of the request in ASP.NET Core 5 Web API
[英]How do I retrieve body values from an HTTP POST request in an ASP.NET Web API ValueProvider?
我想發送一個 HTTP POST 請求,其正文包含構成一篇簡單博客文章的信息,沒什么特別的。
我在這里讀到,當您想在 Web API 中綁定復雜類型(即不是string
、 int
等的類型)時,一個好的方法是創建自定義 model 活頁夾。
我有一個自定義 model 活頁夾 ( BlogPostModelBinder
),它又使用一個自定義值提供程序 ( BlogPostValueProvider
)。 我不明白的是,我應該如何以及在何處能夠從BlogPostValueProvider
的請求正文中檢索數據?
在 model 活頁夾中,這是我認為例如檢索標題的正確方法。
public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
...
var title= bindingContext.ValueProvider.GetValue("Title");
...
}
而 BlogPostValueProvider 看起來像這樣:
public class BlogPostValueProvider : IValueProvider
{
public BlogPostValueProvider(HttpActionContext actionContext)
{
// I can find request header information in the actionContext, but not the body.
}
public ValueProviderResult GetValue(string key)
{
// In some way return the value from the body with the given key.
}
}
這可能可以通過更簡單的方式解決,但由於我正在探索 Web API,所以讓它工作會很好。
我的問題只是我找不到請求正文的存儲位置。
感謝您的指導!
這是來自Rick Strahl的博客文章 。 他的帖子幾乎回答了你的問題。 為了使他的代碼適應您的需求,您將執行以下操作。
在值提供程序的構造函數中,像這樣讀取請求體。
Task<string> content = actionContext.Request.Content.ReadAsStringAsync();
string body = content.Result;
以 Alex 的回答為基礎,在獲得 Raw 身體后,您可以使用 Newtonsoft 對其進行去序列化(無需在博客文章中做任何復雜的事情):
Task<string> content = actionContext.Request.Content.ReadAsStringAsync();
string body = content.Result;
var deserializedObject = JsonConvert.DeserializeObject<YourClassHere>(body.ToString());
https://www.newtonsoft.com/json/help/html/deserializeobject.htm
我需要在ActionFilterAttribute中執行此操作以進行日志記錄,我找到的解決方案是在actionContext中使用ActionArguments,如
public class ExternalApiTraceAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
...
var externalApiAudit = new ExternalApiAudit()
{
Method = actionContext.Request.Method.ToString(),
RequestPath = actionContext.Request.RequestUri.AbsolutePath,
IpAddresss = ((HttpContextWrapper)actionContext.Request.Properties["MS_HttpContext"]).Request.UserHostAddress,
DateOccurred = DateTime.UtcNow,
Arguments = Serialize(actionContext.ActionArguments)
};
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.