我通过传入序列化的 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;
}
}
}
我设法通过HttpContext.Current.Request.InputStream获得它
在这种情况下,
使用 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
}
}