Start learning free

LESSON 6 OF 173 · BACKEND: HOW THE WEB WORKS

Headers in C#

Practice

A response is more than its body. Before the body come the headers: lines of Name: value about the body, like the writing on an envelope around a letter. In C#, the headers about the body are in response.Content.Headers. The header Content-Type says what kind of body this is: text/html for a web page, application/json for JSON. Its .MediaType is that kind alone, without any ; charset= part.

Requests carry headers too, and you can add your own: build the request as an HttpRequestMessage, add headers to its Headers, then send it with SendAsync. The Accept header tells the server which kind of answer you want. The request stays in your variable after it is sent, so you can read back the headers it carried. For example, to send an Accept-Language header that asks for French, and check that it went out:

var ask = new HttpRequestMessage(HttpMethod.Get, SUPPLIER + "/catalog");
ask.Headers.Add("Accept-Language", "fr");
var reply = await http.SendAsync(ask);
Console.WriteLine(ask.Headers.AcceptLanguage);

When you add no Accept header, HttpClient sends none, and a request without Accept means anything will do. Your script asks for two paths and prints what their headers say:

GET /                                    →  Content-Type: text/html; charset=utf-8
GET /prices  (Accept: application/json)  →  media type: application/json
Body: Supplier API. Try /prices
Content-Type: text/html; charset=utf-8
Sent Accept: application/json
Got Content-Type: application/json

Your task: the starting code asks for the home page and prints its body. Print its Content-Type. Then build a request for /prices with an Accept header for JSON, send it, and print the Accept header that went out and the media type of the Content-Type that came back.


Assignment
Follow the Coding Tutorial to read the Content-Type of two answers and send an Accept header of your own.


Hint
response.Content.Headers.ContentType came back; request.Headers.Accept went out. response already exists, so the second answer goes into it without var.


STEP 1 OF 6
    Ctrl + Enter to check

    Web Headers in C#

    Keep going with C#1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free