sourcecode

HttpResponseMessage 헤더에 Content-Type 헤더를 설정할 수 없습니까?

codebag 2023. 7. 12. 23:46
반응형

HttpResponseMessage 헤더에 Content-Type 헤더를 설정할 수 없습니까?

ASP.NET WebApi를 사용하고 있습니다.컨트롤러 중 하나에서 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를 통해 브라우저에서 해당 위치에 PUT하면 다음과 같은 예외가 표시됩니다.

헤더 이름을 잘못 사용했습니다.요청 헤더가 HttpRequestMessage, 응답 헤더는 HttpResponseMessage, 내용 헤더는 HttpContent 객체와 함께 사용되는지 확인합니다.

하지만 그렇지 않나요?Content-Type응답에 대해 완벽하게 유효한 헤더?이 예외가 발생하는 이유는 무엇입니까?

HttpContent 보기머리글.내용 유형 속성:

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.
}

ASP 웹 API에 누락된 것이 있습니다.EmptyContenttype. 내용별 헤더를 모두 허용하면서 빈 본문을 보낼 수 있습니다.

다음 클래스를 코드 어딘가에 넣습니다.

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 (상속하기 때문에) 많은 코드를 실행하는 헤비 클래스입니다.
    • 그래서 몇 나노초를 절약합시다.
  • StringContent쓸모없는/문제가 있는 헤더를 추가합니다.Content-Type: plain/text; charset=...
    • 네트워크 바이트 몇 개를 절약해 보겠습니다.

언급URL : https://stackoverflow.com/questions/13377957/cant-set-content-type-header-on-httpresponsemessage-headers

반응형