Benutzer:MovGP0/ASP.NET Core/Routing

aus Wikipedia, der freien Enzyklopädie
Zur Navigation springen Zur Suche springen
   MovGP0        Über mich        Hilfen        Artikel        Weblinks        Literatur        Zitate        Notizen        Programmierung        MSCert        Physik      

Routing in ASP.NET Core

[Bearbeiten | Quelltext bearbeiten]
Default route
// app.UseMvc(routes => { routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); });
app.UseMvcWithDefaultRoute();
Route Builder
var routes = new RouteBuilder(app);
routes.DefaultHandler = new MvcRouteHandler(...);
routes.MapRoute("blog", "blog/{*article}", defaults: new { controller = "Blog", action = "Article" });
routes.MapRoute("default", "{controller=Home}/{action=Index}/{id?}"); // default route
var routeCollection = routes.Build()
app.UseRouter(routeCollection);
public sealed class HiController
{
    // GET: /hi
    public IActionResult Get() => Ok("Hello");
}
public sealed class TestController : Controller
{
    // /hello
    [Route("/hello")]
    public IActionResult Hello()
        => Ok("Hello");

    // GET: /hi
    [Route("/hi")]
    [HttpGet]
    public IActionResult Hi()
        => Ok("Hi");

    // GET: /hi
    [HttpGet("/hi")]
    public IActionResult Hi()
        => Ok("Hi");
}
//Route prefix
[Route("test")]
public sealed class TestController : Controller
{
    //You can have multiple routes on an action
    [Route("")] // /test
    [Route("hello")] // /test/hello
    public IActionResult Hello()
        => Ok("Hello");

    // Maps to both:
    // /test/hi, and:
    // /hi
    [Route("/hi")] // Overrides the prefix with /, you can also use ~/
    [Route("hi")]
    public IActionResult Hi()
        => Ok("Hi");

    // /test/greet/Joonas -> maps Joonas to the name parameter
    [Route("greet/{name}")]
    public IActionResult Greet(string name)
        => Ok($"Hello {name}!");

    //Parameters can be optional
    // /test/greetopt -> name == null
    // /test/greetopt/Joonas -> name == Joonas
    [Route("greetopt/{name?}")]
    public IActionResult GreetOptional(string name)
        => Ok(name == null ? "No name" : "Hi!");
}
// You can use [controller], [action], and [area] to create generic templates
[Route("[controller]/[action]")]
public sealed class MyController : Controller
{
    // /my/info
    public IActionResult Info()
        => Ok("Info");

    // /my/i
    [Route("/[controller]/i")]
    public IActionResult Info2()
        => Ok("Info2");
}
[Route("user")]
public sealed class SelectionController : Controller
{
    //You can use constraints to influence route selection
    //Do not use for validation!
    // /user/123
    [Route("{id:int}")]
    public IActionResult Int(int id)
        => Ok($"Looked up user id {id}");

    // /user/foo
    [Route("{name:alpha}")]
    public IActionResult String(string name)
        => Ok($"User name {name}");
}

|}