![](/img/trans.png)
[英]WebAPI post action complex type Parameter doesn't invoke custom MediaTypeFormatter and remains null
[英]WebApi Custom MediaTypeFormatter get posted parameters
我通過傳遞序列化的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
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.