Свойство Headers
Правила те же, что у
заголовков запроса:
Content-Type принадлежит
content.Headers.
Синтаксис
response.Headers.TryAddWithoutValidation("Name", "abcde");
Пример
Давайте добавить заголовок
Name к ответу:
using System;
using System.Net;
using System.Net.Http;
class Program
{
static void Main()
{
HttpResponseMessage response =
new HttpResponseMessage(HttpStatusCode.OK);
bool res = response.Headers.TryAddWithoutValidation("Name", "abcde");
Console.WriteLine(res);
}
}
Результат выполнения кода:
True
Пример
Давайте задать Content-Type
у тела ответа:
using System;
using System.Net;
using System.Net.Http;
class Program
{
static void Main()
{
HttpResponseMessage response =
new HttpResponseMessage(HttpStatusCode.OK);
response.Content = new StringContent("abcde");
response.Content.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue("text/plain");
string res = response.Content.Headers.ContentType.MediaType;
Console.WriteLine(res);
}
}
Результат выполнения кода:
"text/plain"
Пример
Давайте добавить Content-Type
в response.Headers:
using System;
using System.Net;
using System.Net.Http;
class Program
{
static void Main()
{
HttpResponseMessage response =
new HttpResponseMessage(HttpStatusCode.OK);
try
{
response.Headers.Add("Content-Type", "text/plain");
}
catch (InvalidOperationException)
{
Console.WriteLine("fail");
}
}
}
Результат выполнения кода:
"fail"
Смотрите также
-
Content,
тело ответа -
Headers запроса,
заголовки запроса -
HttpResponseMessage,
обзор -
StatusCode,
код ответа