如何在ASP.NET WebAPI MediaTypeFormatter中检索HTTP请求方法?

时间:2012-08-08 07:36:23

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

我想在ASP.NET WebAPI函数返回JSON时抛出异常,其中值为IEnumerable,HTTP请求方法为GET - hopefully to stop any JSON being generated where the top level is an array

我试图通过创建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();
        }
        ...
    }
}

1 个答案:

答案 0 :(得分:8)

可以添加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时,请求将有一个值。