[英]How do I retrieve the HTTP request method in an ASP.NET WebAPI MediaTypeFormatter?
当ASP.NET WebAPI函数返回JSON(其中值为IEnumerable且HTTP请求方法为GET)时,我想引发异常- 希望停止在顶级是数组的情况下生成任何JSON 。
我试图通过创建MediaTypeFormatter来做到这一点。 我能做到吗? 我还有其他方法可以做到这一点吗? 谢谢。
就像是:
public class CustomFormatter : MediaTypeFormatter
{
public override Task WriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, TransportContext transportContext)
{
// Retrieve value for isGetRequest somehow...
if (value is IEnumerable && isGetRequest)
{
throw new InvalidOperationException();
}
...
}
}
可能已经添加了GetPerRequestFormatterInstance
方法,并且可以重写该方法:
public class CustomFormatter : MediaTypeFormatter
{
private HttpRequestMessage _request;
private CustomFormatter(HttpRequestMessage request)
{
_request = request;
}
public override MediaTypeFormatter GetPerRequestFormatterInstance(Type type, HttpRequestMessage request, MediaTypeHeaderValue mediaType)
{
return new CustomFormatter(request);
}
..........
因此,如果执行此操作,则在WriteToStreamAsync
,请求将具有一个值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.