80

ASP.NETWebApiを使用してRESTfulAPIを作成しています。コントローラーの1つでPUTメソッドを作成していますが、コードは次のようになっています。

public HttpResponseMessage Put(int idAssessment, int idCaseStudy, string value) {
    var response = Request.CreateResponse();
    if (!response.Headers.Contains("Content-Type")) {
        response.Headers.Add("Content-Type", "text/plain");
    }

    response.StatusCode = HttpStatusCode.OK;
    return response;
}

AJAXを介してブラウザでその場所に配置すると、次の例外が発生します。

誤用されたヘッダー名。リクエストヘッダーがHttpRequestMessageで使用され、レスポンスヘッダーがHttpResponseMessageで使用され、コンテンツヘッダーがHttpContentオブジェクトで使用されていることを確認してください。

しかしContent-Type、応答の完全に有効なヘッダーではありませんか?なぜこの例外が発生するのですか?

4

2 に答える 2

120

HttpContentHeaders.ContentTypeプロパティを見てください:

response.Content.Headers.ContentType = new MediaTypeHeaderValue("text/plain");

if (response.Content == null)
{
    response.Content = new StringContent("");
    // The media type for the StringContent created defaults to text/plain.
}
于 2012-11-14T11:39:59.627 に答える
2

ASP Web APIに何かが欠けています:EmptyContentタイプ。すべてのコンテンツ固有のヘッダーを許可しながら、空の本文を送信できます。

次のクラスをコードのどこかに配置します。

public class EmptyContent : HttpContent
{
    protected override Task SerializeToStreamAsync(Stream stream, TransportContext context)
    {
        return Task.CompletedTask;
    }
    protected override bool TryComputeLength(out long length)
    {
        length = 0L;
        return true;
    }
}

その後、必要に応じて使用してください。これで、追加のヘッダー用のコンテンツオブジェクトができました。

response.Content = new EmptyContent();
response.Content.Headers.LastModified = file.DateUpdatedUtc;

なぜEmptyContent代わりに使用するのnew StringContent(string.Empty)ですか?

  • StringContentは、多くのコードを実行する重いクラスです(継承するためByteArrayContent
    • 数ナノ秒節約しましょう
  • StringContent余分な役に立たない/問題のあるヘッダーを追加します:Content-Type: plain/text; charset=...
    • それでは、ネットワークバイトを数バイト節約しましょう
于 2019-07-12T17:44:20.660 に答える