如何从ASP.NET Web API ValueProvider中的HTTP POST请求中检索正文值?

Jim*_*Aho 12 c# asp.net model-binding value-provider asp.net-web-api

我想发送一个HTTP POST请求,其中包含组成简单博客帖子的信息,没什么特别的.

我读过这里,当你想绑定复杂类型(即一个类型,是不是string,int在网络API等),一个好方法是创建一个自定义模型粘合剂.

我有一个自定义模型binder(BlogPostModelBinder),后者又使用自定义Value Provider(BlogPostValueProvider).我不明白的是,我将如何以及在何处从请求正文中检索数据BlogPostValueProvider

在模型绑定器内部,我认为这是检索标题的正确方法.

public bool BindModel(HttpActionContext actionContext, ModelBindingContext bindingContext)
{
   ...
   var title= bindingContext.ValueProvider.GetValue("Title");
   ...
}
Run Code Online (Sandbox Code Playgroud)

而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.
    }
 }
Run Code Online (Sandbox Code Playgroud)

这可能是一种更容易解决的方法,但是因为我正在探索Web API,所以最好让它工作.

我的问题很简单,我找不到请求体的存储位置.

谢谢你的指导!

小智 20

这是来自Rick Strahl 的博客文章.他的帖子几乎回答了你的问题.为了使他的代码适应您的需求,您将执行以下操作.

在值提供程序的构造函数中,像这样读取请求体.

Task<string> content = actionContext.Request.Content.ReadAsStringAsync();
string body = content.Result;
Run Code Online (Sandbox Code Playgroud)

  • 永远不要使用.Result,总是使用await,否则你会遇到死锁/饥饿 (2认同)