How to get HTTP request method in ASP.NET WebAPI MediaTypeFormatter?

I would like to make an exception when the ASP.NET WebAPI function returns JSON, where this value is IEnumerable, and the HTTP request method is GET - I hope to stop any JSON generated where the top level is an array .

I tried to do this by creating MediaTypeFormatter. Can I do it? Is there any other way I can do this? Thanks.

Sort of:

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
source share
1 answer

Perhaps since the method has GetPerRequestFormatterInstancebeen added and can be overridden:

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 .

+7

Source: https://habr.com/ru/post/1614583/


All Articles