Kurse:HTTP Code Übungen: Unterschied zwischen den Versionen

Aus ahrensburg.city
Zur Navigation springen Zur Suche springen
Die Seite wurde neu angelegt: „== Übungen zu HTTP-Protokoll und ASP.NET Core == === Übung 1: HTTP-Antwort beobachten im Browser === # Öffne deine Beispiel-Webseite in Chrome oder Firefox. # Aktiviere die Entwickler-Tools und wechsle zum Netzwerk-Tab (siehe §19.6 in LaunchCode) :contentReference[oaicite:1]{index=1}. # Lade die Seite neu und identifiziere: : * Eine GET‑Anfrage für das HTML-Dokument : * Eine GET‑Anfrage für eine CSS-Datei : * Eine GET‑Anfrage für ein Bild #…“
 
Keine Bearbeitungszusammenfassung
Zeile 1: Zeile 1:
== Übungen zu HTTP-Protokoll und ASP.NET Core ==
= HTTP-Protokoll (Hypertext Transfer Protocol) =


=== Übung 1: HTTP-Antwort beobachten im Browser ===
== Überblick ==
# Öffne deine Beispiel-Webseite in Chrome oder Firefox.
* HTTP ist ein zustandsloses Protokoll zur Übertragung von Hypertext (z. B. HTML) im Internet.
# Aktiviere die Entwickler-Tools und wechsle zum Netzwerk-Tab (siehe §19.6 in LaunchCode) :contentReference[oaicite:1]{index=1}.
* Client-Server-Modell: Der Client (z. B. Browser) sendet Anfragen, der Server antwortet.
# Lade die Seite neu und identifiziere:
* Jede Anfrage ist unabhängig von vorherigen (stateless).
: * Eine GET‑Anfrage für das HTML-Dokument
: * Eine GET‑Anfrage für eine CSS-Datei
: * Eine GET‑Anfrage für ein Bild
# Notiere für jede Anfrage:
: * Statuscode, z. B. 200 oder 404
: * Content-Type und Größe (Bytes)
# Experimentiere:
: * Ändere im HTML die URL einer CSS-Datei auf einen falschen Namen
: * Lade die Seite erneut und erkläre, wie sich das Verhalten ändert :contentReference[oaicite:2]{index=2}


=== Übung 2: HTTP‑Response‑Analyse ===
== Anfragemodell ==
Analysiere diese Beispiel-Antwort:
* '''Client Request''': Der Client sendet eine HTTP-Anfrage.
* '''Server Response''': Der Server verarbeitet die Anfrage und antwortet mit Ressourcen oder Fehlermeldungen.


<pre>
== HTTP-Server ==
HTTP/1.1 404 Not Found
'''Definition''': Software, die HTTP-Anfragen verarbeitet und Antworten liefert.
Date: Sat, 21 Jun 2025 20:38:53 +0000
Server: Apache/2.2.3 (CentOS)
Content-Length: 67365
Keep-Alive: timeout=37, max=95
Connection: Keep-alive
Content-Type: text/html
</pre>


Beantworte:
'''Beispiele''':
# Welche HTTP-Version wird verwendet?
* Apache HTTP Server
# Wurde der Inhalt erfolgreich gesendet?
* Nginx
# Wie groß ist das Dokument?
* Microsoft IIS
# Ist die Verbindung persistent?
* Kestrel (ASP.NET Core)
# Welcher Medientyp wird zurückgesendet?
# Welche Server-Software und Version?
# Ändert sich der ETag bei neuen Ressourcenversionen?
(Lösungsvorlage siehe UMass-Quelle) :contentReference[oaicite:3]{index=3}


=== Übung 3: Minimal-HTTP‑Server mit ASP.NET Core ===
'''Kestrel''':
Erstelle eine minimalistische ASP.NET Core‑App (ohne MVC oder Razor), die:
* Cross-Platform Webserver in ASP.NET Core
* Auf GET-Anfragen an `/` antwortet mit: `Hello, World!`
* Leichtgewichtig und leistungsfähig
* Angabe:
 
<pre>
== Ablauf von Anfrage und Antwort mit Kestrel ==
# Client sendet Anfrage
# Kestrel empfängt und leitet sie an Middleware weiter
# Middleware verarbeitet Anfrage
# Anwendung erzeugt Antwort
# Kestrel sendet Antwort zurück an den Client
 
== Browser & HTTP ==
* Browser fordern HTML, CSS, JS, Bilder über HTTP an
* Klick auf Link → HTTP-Request → Server → Response → Darstellung im Browser
 
== HTTP-Anfragen in Chrome Dev Tools beobachten ==
* Öffnen: F12 oder Ctrl+Shift+I (Cmd+Option+I auf Mac)
* Reiter „Network“ → Details zu:
** Headers
** Response
** Timing
 
== Aufbau einer HTTP-Antwort ==
'''Format''':
HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 137
 
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
 
'''Wichtige Header''':
* Content-Type: Typ der Ressource (z. B. text/html)
* Content-Length: Größe der Antwort
* Server: Infos zum Server
* Set-Cookie: Setzt Cookies im Client
* Cache-Control: Caching-Strategie
 
== Kestrel Standard-Header ==
* Content-Type: z. B. text/html, application/json
* Server: „Kestrel“
* Date: Zeitstempel der Antwort
 
== HTTP-Statuscodes ==
=== Kategorien ===
* '''1xx''': Information
* '''2xx''': Erfolg
* '''3xx''': Weiterleitung
* '''4xx''': Clientfehler
* '''5xx''': Serverfehler
 
=== Gängige Codes ===
* 200 OK
* 201 Created
* 204 No Content
* 400 Bad Request
* 401 Unauthorized
* 403 Forbidden
* 404 Not Found
* 500 Internal Server Error
* 503 Service Unavailable
 
== ASP.NET Core Codebeispiele ==
=== Beispiel 1: Antwort-Header setzen ===
<syntaxhighlight lang="csharp">
var builder = WebApplication.CreateBuilder(args);
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
var app = builder.Build();


app.Run(async context => {
app.Run(async (HttpContext context) =>
     context.Response.Headers["Content-Type"] = "text/plain";
{
     await context.Response.WriteAsync("Hello, World!");
    context.Response.Headers["MyKey"] = "my value";
    context.Response.Headers["Server"] = "My server";
     context.Response.Headers["Content-Type"] = "text/html";
     await context.Response.WriteAsync("<h1>Hello</h1>");
    await context.Response.WriteAsync("<h2>World</h2>");
});
});


app.Run();
app.Run();
</pre>
</syntaxhighlight>
 
=== Beispiel 2: Statuscode setzen ===
<syntaxhighlight lang="csharp">
app.Run(async (HttpContext context) =>
{
    context.Response.StatusCode = 200;
    await context.Response.WriteAsync("Hello");
    await context.Response.WriteAsync(" World");
});
</syntaxhighlight>
 
== HTTP-Request-Aufbau ==
* '''Startzeile''': Methode, URI, HTTP-Version
* '''Header''': z. B. User-Agent, Accept, Authorization
* '''Leerzeile'''
* '''Body (optional)''': z. B. JSON, Formulardaten
 
=== Beispiel: GET-Anfrage ===
GET /products?category=electronics&brand=apple HTTP/1.1
Host: example.com
 
=== Beispiel: POST-Anfrage ===
POST /login HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
 
username=john&password=secret
 
== Query Strings ==
* Parameter in URL übergeben
* Beispiel:
https://example.com/products?category=electronics&brand=apple
 
== Zugriff auf Request-Details in ASP.NET Core ==
=== Beispiel: Pfad und Methode auslesen ===
<syntaxhighlight lang="csharp">
app.Run(async (HttpContext context) =>
{
    string path = context.Request.Path;
    string method = context.Request.Method;
    context.Response.Headers["Content-type"] = "text/html";
    await context.Response.WriteAsync($"<p>{path}</p>");
    await context.Response.WriteAsync($"<p>{method}</p>");
});
</syntaxhighlight>
 
=== Beispiel: Query-Parameter auslesen ===
<syntaxhighlight lang="csharp">
app.Run(async (HttpContext context) =>
{
    if (context.Request.Method == "GET" &&
        context.Request.Query.ContainsKey("id"))
    {
        string id = context.Request.Query["id"];
        await context.Response.WriteAsync($"<p>ID: {id}</p>");
    }
});
</syntaxhighlight>
 
=== Beispiel: User-Agent anzeigen ===
<syntaxhighlight lang="csharp">
app.Run(async (HttpContext context) =>
{
    if (context.Request.Headers.ContainsKey("User-Agent"))
    {
        string agent = context.Request.Headers["User-Agent"];
        await context.Response.WriteAsync($"<p>{agent}</p>");
    }
});
</syntaxhighlight>


=== Übung 4: Antwort-Header anpassen ===
== HTTP-Methoden ==
Erweitere Übung 3 so, dass:
* '''GET''': Daten abfragen, sichtbar in URL, cachebar, sicher
* Ein eigener Header `X‑Powered‑By` mit Wert `MyServer` gesetzt wird.
* '''POST''': Daten senden (z. B. Formulare), im Body, nicht idempotent
* Der Content-Type auf `text/html` geändert wird und das HTML `<h1>Hallo Welt!</h1>` zurückgeliefert wird.


=== Übung 5: HTTP‑Statuscodes dynamisch setzen ===
== GET vs POST ==
Erstelle eine Route `/status`, die anhand eines Query‑Parameters `code` den Status festlegt:
'''GET''':
* Daten in URL
* cachebar, idempotent
* nicht für sensible Daten


* Beispielaufruf: `/status?code=201`
'''POST''':
* Dein Code:
* Daten im Body
<pre>
* sicherer für Passwörter
var code = int.Parse(context.Request.Query["code"]);
* nicht idempotent
context.Response.StatusCode = code;
await context.Response.WriteAsync($"Status: {code}");
</pre>


Teste mit verschiedenen Codes wie 200, 400, 404, 500.
== Tool: Postman ==
'''Verwendung''':
* HTTP-Requests (GET, POST, usw.) erstellen
* Header & Body anpassen
* Antwort inspizieren: Statuscode, Header, Body


=== Übung 6: GET‑Parameter auslesen ===
'''Ablauf''':
Baue eine Route `/hello`, die einen Query‑Parameter `name` erwartet:
# Öffnen → Neue Anfrage
# Methode + URL eingeben (z. B. https://localhost:7070/api/products)
# Optional: Header / Body hinzufügen
# "Send" klicken → Antwort wird unten angezeigt


* Beispiel: `/hello?name=Alice`
== Zusammenfassung ==
* Antwort: `<p>Hello, Alice!</p>`
* HTTP = Grundlage der Webkommunikation
* Beispiel-Code:
* Zustandslos, Anfrage-Antwort-Modell
<pre>
* Statuscodes geben Antwortstatus an
if (context.Request.Path == "/hello" && context.Request.Method == "GET") {
* ASP.NET Core erlaubt präzise Steuerung von Anfragen & Antworten
  var name = context.Request.Query["name"];
* Tools wie Postman helfen beim Testen von APIs
  await context.Response.WriteAsync($"<p>Hello, {name}!</p>");
}

Version vom 23. Juni 2025, 19:38 Uhr

HTTP-Protokoll (Hypertext Transfer Protocol)

Überblick

  • HTTP ist ein zustandsloses Protokoll zur Übertragung von Hypertext (z. B. HTML) im Internet.
  • Client-Server-Modell: Der Client (z. B. Browser) sendet Anfragen, der Server antwortet.
  • Jede Anfrage ist unabhängig von vorherigen (stateless).

Anfragemodell

  • Client Request: Der Client sendet eine HTTP-Anfrage.
  • Server Response: Der Server verarbeitet die Anfrage und antwortet mit Ressourcen oder Fehlermeldungen.

HTTP-Server

Definition: Software, die HTTP-Anfragen verarbeitet und Antworten liefert.

Beispiele:

  • Apache HTTP Server
  • Nginx
  • Microsoft IIS
  • Kestrel (ASP.NET Core)

Kestrel:

  • Cross-Platform Webserver in ASP.NET Core
  • Leichtgewichtig und leistungsfähig

Ablauf von Anfrage und Antwort mit Kestrel

  1. Client sendet Anfrage
  2. Kestrel empfängt und leitet sie an Middleware weiter
  3. Middleware verarbeitet Anfrage
  4. Anwendung erzeugt Antwort
  5. Kestrel sendet Antwort zurück an den Client

Browser & HTTP

  • Browser fordern HTML, CSS, JS, Bilder über HTTP an
  • Klick auf Link → HTTP-Request → Server → Response → Darstellung im Browser

HTTP-Anfragen in Chrome Dev Tools beobachten

  • Öffnen: F12 oder Ctrl+Shift+I (Cmd+Option+I auf Mac)
  • Reiter „Network“ → Details zu:
    • Headers
    • Response
    • Timing

Aufbau einer HTTP-Antwort

Format:

HTTP/1.1 200 OK
Content-Type: text/html
Content-Length: 137
<html>
<body>

Hello, World!

</body>
</html>

Wichtige Header:

  • Content-Type: Typ der Ressource (z. B. text/html)
  • Content-Length: Größe der Antwort
  • Server: Infos zum Server
  • Set-Cookie: Setzt Cookies im Client
  • Cache-Control: Caching-Strategie

Kestrel Standard-Header

  • Content-Type: z. B. text/html, application/json
  • Server: „Kestrel“
  • Date: Zeitstempel der Antwort

HTTP-Statuscodes

Kategorien

  • 1xx: Information
  • 2xx: Erfolg
  • 3xx: Weiterleitung
  • 4xx: Clientfehler
  • 5xx: Serverfehler

Gängige Codes

  • 200 OK
  • 201 Created
  • 204 No Content
  • 400 Bad Request
  • 401 Unauthorized
  • 403 Forbidden
  • 404 Not Found
  • 500 Internal Server Error
  • 503 Service Unavailable

ASP.NET Core Codebeispiele

Beispiel 1: Antwort-Header setzen

var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();

app.Run(async (HttpContext context) =>
{
    context.Response.Headers["MyKey"] = "my value";
    context.Response.Headers["Server"] = "My server";
    context.Response.Headers["Content-Type"] = "text/html";
    await context.Response.WriteAsync("<h1>Hello</h1>");
    await context.Response.WriteAsync("<h2>World</h2>");
});

app.Run();

Beispiel 2: Statuscode setzen

app.Run(async (HttpContext context) =>
{
    context.Response.StatusCode = 200;
    await context.Response.WriteAsync("Hello");
    await context.Response.WriteAsync(" World");
});

HTTP-Request-Aufbau

  • Startzeile: Methode, URI, HTTP-Version
  • Header: z. B. User-Agent, Accept, Authorization
  • Leerzeile
  • Body (optional): z. B. JSON, Formulardaten

Beispiel: GET-Anfrage

GET /products?category=electronics&brand=apple HTTP/1.1
Host: example.com

Beispiel: POST-Anfrage

POST /login HTTP/1.1
Host: example.com
Content-Type: application/x-www-form-urlencoded
username=john&password=secret

Query Strings

  • Parameter in URL übergeben
  • Beispiel:
https://example.com/products?category=electronics&brand=apple

Zugriff auf Request-Details in ASP.NET Core

Beispiel: Pfad und Methode auslesen

app.Run(async (HttpContext context) =>
{
    string path = context.Request.Path;
    string method = context.Request.Method;
    context.Response.Headers["Content-type"] = "text/html";
    await context.Response.WriteAsync($"<p>{path}</p>");
    await context.Response.WriteAsync($"<p>{method}</p>");
});

Beispiel: Query-Parameter auslesen

app.Run(async (HttpContext context) =>
{
    if (context.Request.Method == "GET" &&
        context.Request.Query.ContainsKey("id"))
    {
        string id = context.Request.Query["id"];
        await context.Response.WriteAsync($"<p>ID: {id}</p>");
    }
});

Beispiel: User-Agent anzeigen

app.Run(async (HttpContext context) =>
{
    if (context.Request.Headers.ContainsKey("User-Agent"))
    {
        string agent = context.Request.Headers["User-Agent"];
        await context.Response.WriteAsync($"<p>{agent}</p>");
    }
});

HTTP-Methoden

  • GET: Daten abfragen, sichtbar in URL, cachebar, sicher
  • POST: Daten senden (z. B. Formulare), im Body, nicht idempotent

GET vs POST

GET:

  • Daten in URL
  • cachebar, idempotent
  • nicht für sensible Daten

POST:

  • Daten im Body
  • sicherer für Passwörter
  • nicht idempotent

Tool: Postman

Verwendung:

  • HTTP-Requests (GET, POST, usw.) erstellen
  • Header & Body anpassen
  • Antwort inspizieren: Statuscode, Header, Body

Ablauf:

  1. Öffnen → Neue Anfrage
  2. Methode + URL eingeben (z. B. https://localhost:7070/api/products)
  3. Optional: Header / Body hinzufügen
  4. "Send" klicken → Antwort wird unten angezeigt

Zusammenfassung

  • HTTP = Grundlage der Webkommunikation
  • Zustandslos, Anfrage-Antwort-Modell
  • Statuscodes geben Antwortstatus an
  • ASP.NET Core erlaubt präzise Steuerung von Anfragen & Antworten
  • Tools wie Postman helfen beim Testen von APIs