Kurs:Täglich Controllers Übungen
Zur Navigation springen
Zur Suche springen
ASP.NET Core MVC: Controller & Action Methods – Code-Spickzettel
1. Einfacher Controller mit Action Methods
// HomeController.cs
namespace MyApp.Controllers
{
[Controller]
public class HomeController : Controller
{
[Route("home")]
[Route("/")]
public string Index()
{
return "Hello from Index";
}
[Route("about")]
public string About()
{
return "Hello from About";
}
[Route("contact-us/{mobile:regex(^\\d{10}$)}")]
public string Contact(string mobile)
{
return $"Contact: {mobile}";
}
}
}
2. ContentResult: Rohdaten zurückgeben
[Route("rawtext")]
public ContentResult RawText()
{
return Content("Nur Text!", "text/plain");
}
[Route("html")]
public ContentResult HtmlExample()
{
return Content("<h2>Hallo als HTML</h2>", "text/html");
}
3. JsonResult: JSON zurückgeben
[Route("person")]
public JsonResult Person()
{
var person = new { Id = 1, Name = "Anna", Age = 23 };
return Json(person); // Content-Type: application/json
}
4. File Results: Dateien bereitstellen
// Aus wwwroot (z.B. /wwwroot/sample.pdf)
[Route("file-download")]
public VirtualFileResult Download1()
{
return File("/sample.pdf", "application/pdf");
}
// Von Festplatte (Vorsicht bei Pfaden!)
[Route("file-download2")]
public PhysicalFileResult Download2()
{
return PhysicalFile(@"c:\files\sample.pdf", "application/pdf");
}
// Aus Speicher (byte[])
[Route("file-download3")]
public FileContentResult Download3()
{
byte[] data = System.IO.File.ReadAllBytes(@"c:\files\sample.pdf");
return File(data, "application/pdf");
}
5. IActionResult: Verschiedene Rückgaben möglich
[Route("validate")]
public IActionResult Validate(int bookid = 0)
{
if (bookid <= 0)
return BadRequest("Book id ungültig");
if (bookid > 1000)
return NotFound("Book id zu groß");
return File("/sample.pdf", "application/pdf");
}
6. Status Code Results
// 400 Bad Request
return BadRequest("Fehlerhafte Anfrage!");
// 404 Not Found
return NotFound("Nicht gefunden!");
// 401 Unauthorized
return Unauthorized();
// Beliebiger Code
return StatusCode(418, "Ich bin eine Teekanne"); // RFC Joke ;-)
7. Redirects
// Zu einer URL
return Redirect("/home");
// Zu einer Action im gleichen Controller
return RedirectToAction("About");
// Zu einer Action in anderem Controller
return RedirectToAction("Details", "Books", new { id = 42 });
// Nur lokal (Schutz gegen Open Redirects)
return LocalRedirect("/safe-page");
// Permanent
return RedirectPermanent("/neue-seite");
8. Übungen
- Schreibe einen Controller namens `ProductController` mit Action Methods:
- `List()` → gibt einen Text "Alle Produkte" zurück
- `Details(int id)` → gibt JSON zurück: { "id": id, "name": "Produktname" }
- `DownloadManual()` → gibt eine Datei aus wwwroot zurück
- Baue Routing mit [Route] Attributen ein.
- Füge eine Action hinzu, die einen 404-Status zurückgibt, falls die id > 100 ist.
9. Wichtige Interview-Stichworte
- Controller: Endet immer auf *Controller*
- Action-Methoden: public, beliebiger Name
- Rückgabewerte: ContentResult, JsonResult, FileResult, IActionResult, RedirectResult usw.
- Attribute Routing: [Route], [HttpGet], [HttpPost], ...
- Statuscodes: 200, 400, 401, 404 etc. per Helper-Methoden