简体   繁体   中英

How do I retrieve the HTTP request method in an ASP.NET WebAPI MediaTypeFormatter?

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

I've tried to do this by creating a MediaTypeFormatter. Am I able to do this? Is there another way I can go about doing this? Thanks.

Something like:

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();
        }
        ...
    }
}

It is possible as GetPerRequestFormatterInstance method has been added and can be overriden:

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);
    }
    ..........

So if you do that, then at the time of WriteToStreamAsync , request will have a value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM