5

カスタム メディア フォーマッタを実装しましたが、クライアントが具体的に「csv」形式を要求した場合にうまく機能します。

次のコードで API コントローラーをテストしました。

        HttpClient client = new HttpClient();
        // Add the Accept header
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("text/csv"));

ただし、Web ブラウザーから同じ URL を開くと、CSV ではなく JSON が返されます。これはおそらく、呼び出し元によって特に指定されていない限り、JSON を既定のメディア フォーマッタとして設定する標準の ASP.NET WebAPI 構成が原因です。私が持っている他のすべてのWebサービスでこのデフォルトの動作が必要ですが、CSVを返すこの単一の操作では必要ありません。デフォルトのメディア ハンドラーを、実装した CSV ハンドラーにしたいと考えています。デフォルトで CSV を返し、クライアントから要求された場合に JSON/XML のみを返すように、コントローラーのエンドポイントを構成するにはどうすればよいですか?

4

1 に答える 1

0

どのバージョンの Web API を使用していますか?

バージョンを使用している場合は、以下のような5.0新しいIHttpActionResultベースのロジックを使用できます。

public IHttpActionResult Get()
{
    MyData someData = new MyData();

    // creating a new list here as I would like CSVFormatter to come first. This way the DefaultContentNegotiator
    // will behave as before where it can consider CSVFormatter to be the default one.
    List<MediaTypeFormatter> respFormatters = new List<MediaTypeFormatter>();
    respFormatters.Add(new MyCsvFormatter());
    respFormatters.AddRange(Configuration.Formatters);

    return new NegotiatedContentResult<MyData>(HttpStatusCode.OK, someData,
                    Configuration.Services.GetContentNegotiator(), Request, respFormatters);
}

Web API のバージョンを使用している場合4.0は、次のことができます。

public HttpResponseMessage Get()
{
    MyData someData = new MyData();

    HttpResponseMessage response = new HttpResponseMessage();

    List<MediaTypeFormatter> respFormatters = new List<MediaTypeFormatter>();
    respFormatters.Add(new MyCsvFormatter());
    respFormatters.AddRange(Configuration.Formatters);

    IContentNegotiator negotiator = Configuration.Services.GetContentNegotiator();
    ContentNegotiationResult negotiationResult = negotiator.Negotiate(typeof(MyData), Request, respFormatters);

    if (negotiationResult.Formatter == null)
    {
        response.StatusCode = HttpStatusCode.NotAcceptable;
        return response;
    }

    response.Content = new ObjectContent<MyData>(someData, negotiationResult.Formatter, negotiationResult.MediaType);

    return response;
}
于 2013-10-30T18:44:26.337 に答える