简体   繁体   English

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

[英]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 . 当ASP.NET WebAPI函数返回JSON(其中值为IEnumerable且HTTP请求方法为GET)时,我想引发异常- 希望停止在顶级是数组的情况下生成任何JSON

I've tried to do this by creating a MediaTypeFormatter. 我试图通过创建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: 可能已经添加了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);
    }
    ..........

So if you do that, then at the time of WriteToStreamAsync , request will have a value. 因此,如果执行此操作,则在WriteToStreamAsync ,请求将具有一个值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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