簡體   English   中英

如何在ASP.NET WebAPI MediaTypeFormatter中檢索HTTP請求方法?

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

當ASP.NET WebAPI函數返回JSON(其中值為IEnumerable且HTTP請求方法為GET)時,我想引發異常- 希望停止在頂級是數組的情況下生成任何JSON

我試圖通過創建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();
        }
        ...
    }
}

可能已經添加了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 ,請求將具有一個值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM