반응형
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에 누락된 것이 있습니다.EmptyContent
type. 내용별 헤더를 모두 허용하면서 빈 본문을 보낼 수 있습니다.
다음 클래스를 코드 어딘가에 넣습니다.
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
반응형
'sourcecode' 카테고리의 다른 글
봄의 근원초기화가 더 이상 사용되지 않습니다. (0) | 2023.07.12 |
---|---|
코드(c#)에서 div를 숨기는 방법 (0) | 2023.07.12 |
플라스크 - 잘못된 요청 브라우저(또는 프록시)가 이 서버가 이해할 수 없는 요청을 보냈습니다. (0) | 2023.07.12 |
ansysql INSERT INTO 생성 (0) | 2023.07.12 |
SPARS COLUMN을 사용해야 하는 이유와 시기(SQL SERVER 2008) (0) | 2023.07.12 |