17

我想发送一个 HTTP POST 请求,其正文包含构成简单博客文章的信息,没什么特别的。

我在这里读到,当您想在 Web API 中绑定复杂类型(即不是 的类型stringint)时,一个好方法是创建自定义模型绑定器。

我有一个自定义模型绑定器 ( BlogPostModelBinder),它又使用自定义值提供程序 ( BlogPostValueProvider)。我不明白的是,我应该如何以及在哪里能够从请求正文中检索数据BlogPostValueProvider

在模型活页夹中,我认为这是检索标题的正确方法。

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,让它工作会很好。

我的问题只是我找不到请求正文的存储位置。

感谢您的任何指导!

4

2 回答 2

23

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

在您的值提供者的构造函数中,像这样读取请求正文。

Task<string> content = actionContext.Request.Content.ReadAsStringAsync();
string body = content.Result;
于 2014-08-29T20:53:36.347 回答
2

我需要在 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)
        };
于 2016-11-04T07:10:44.737 回答