【问题标题】:WebApi Custom MediaTypeFormatter get posted parametersWebApi Custom MediaTypeFormatter 获取发布参数
【发布时间】:2014-12-22 13:17:07
【问题描述】:

我通过传入序列化的 JSON DTO 来调用 webapi 上的发布操作。

我还有一个自定义媒体类型格式化程序来加密结果数据。但是在 WriteToStreamAsync 方法中,如何获取发布的参数?

自定义媒体类型格式化程序类

public class JsonFormatter : JsonMediaTypeFormatter
{


    public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
    {
        var taskSource = new TaskCompletionSource<object>();
        try
        {
            if (value != null)
            {
               //How to get posted parameters?
            }
        }
        catch (Exception e)
        {
            taskSource.SetException(e);
        }
        return taskSource.Task;
    }
}

}

【问题讨论】:

    标签: json asp.net-web-api asp.net-web-api2


    【解决方案1】:

    我设法通过 HttpContext.Current.Request.InputStream 得到它

    【讨论】:

      【解决方案2】:

      在这种情况下使用HttpContext.Current 通常不应该工作,因为它并不总是可用于async 调用。

      改为执行以下操作:

          public class JsonFormatter : JsonMediaTypeFormatter
          {
              private readonly HttpRequestMessage request;
      
              public JsonFormatter() { }
              public JsonFormatter(HttpRequestMessage request)
              {
                  this.request = request;
              }
      
              public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
              {
                  return new JsonFormatter(request);
              }
      
              public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
              {
                  // logic referencing this.request
              }
          }
      

      【讨论】:

        猜你喜欢
        • 2013-05-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-05-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-22
        相关资源
        最近更新 更多