我如何检索一个ASP.NET的WebAPI MediaTypeFormatter HTTP请求方法? [英] How do I retrieve the HTTP request method in an ASP.NET WebAPI MediaTypeFormatter?

查看:123
本文介绍了我如何检索一个ASP.NET的WebAPI MediaTypeFormatter HTTP请求方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想,当一个ASP.NET的WebAPI函数返回JSON其中值是IEnumerable和HTTP请求的方法是抛出一个异常GET - 的希望停止任何JSON,其中顶层是一个数组

我试图通过创建MediaTypeFormatter做到这一点。我能够做到这一点?有另一种方法,我可以去这样做?谢谢你。

是这样的:

 公共类的CustomFormatter:MediaTypeFormatter
{
    公众覆盖任务WriteToStreamAsync(类型类型,对象的值,涧流,HttpContentHeaders contentHeaders,TransportContext transportContext)
    {
        //为isGetRequest找回价值莫名其妙...
        如果(值的IEnumerable和放大器;&安培; isGetRequest)
        {
            抛出新的InvalidOperationException异常();
        }
        ...
    }
}


解决方案

GetPerRequestFormatterInstance 方法已经被添加,可以重写它是可能的:

 公共类的CustomFormatter:MediaTypeFormatter
{
    私人的Htt prequestMessage _REQUEST;    私人的CustomFormatter(HTT prequestMessage要求)
    {
        _request =请求;
    }    公众覆盖MediaTypeFormatter GetPerRequestFormatterInstance(类型类型,Htt的prequestMessage要求,MediaTypeHeaderValue mediaType的)
    {
        返回新的CustomFormatter(请求);
    }
    ..........

所以,如果你这样做,那么在时间 WriteToStreamAsync ,请求将有一个值。

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.

这篇关于我如何检索一个ASP.NET的WebAPI MediaTypeFormatter HTTP请求方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆