Aspnetcoremvc PDF
Aspnetcoremvc PDF
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
}
project.json
{
"version": "1.0.0-*",
• Project type "buildOptions": {
"emitEntryPoint": true
• Application or library },
"dependencies": {
• Dependencies "Microsoft.AspNetCore.Mvc": "1.0.0-rc2-*"
},
• Primarily from NuGet "frameworks": {
https://github.com/dotnet/corefx/blob/master/Documentation/architecture/net-platform-standard.md
Platform support for .NET Standard
dotnet restore
• Downloads NuGet dependencies
• Might need a local nuget.config to target nightly builds from myget.org
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<packageSources>
<!--To inherit the global NuGet package sources remove the <clear/> line below -->
<clear />
<add key="dotnet-core" value="https://dotnet.myget.org/F/dotnet-core/api/v3/index.json" />
<add key="AspNetCI" value="https://www.myget.org/F/aspnetcirelease/api/v3/index.json" />
</packageSources>
</configuration>
• Builds project.json.lock
• Snapshot of dependency versions
• Needed to load application
dotnet build / dotnet run / dotnet app.dll
• Builds project, or builds and runs application
• -c indicates configuration (release/debug)
• -f indicates framework to target
• -v emits verbose log output
• Binaries output to ~/bin/<configuration>/<framework> folder
ASP.NET Core
• The new pipeline
• Middleware
• Dependency Injection
• Configuration
Motivation
• Modern web stack
• Modern package system (NuGet)
• Lightweight/composable runtime
• Dependency injection
• Flexible configuration/deployment
"Empty Web Application"
OWIN Middleware Architecture
• Middleware are linked components that process requests
• Application code targeting a framework
Host
OWIN Server
dotnet run
ConfigureServices(…)
Configure(…)
Loading ASP.NET Core
public class Program
{
public static void Main()
{
var host = new WebHostBuilder()
.UseKestrel()
.UseIISIntegration()
.UseStartup<Startup>()
.Build();
app.Use(context, next)
app.Run(context)
Run
namespace Microsoft.AspNetCore.Builder
{
public delegate Task RequestDelegate(HttpContext context);
}
await next();
Console.WriteLine("post");
Console.WriteLine(context.Response.StatusCode);
}
else
{
await next();
}
});
Middleware classes
app.UseMiddleware<InspectionMiddleware>();
services.AddScoped<IMyCustomService, MyCustomService>();
• Singleton
services.AddSingleton<IMyCustomService, MyCustomService>();
Configuration
• web.config is no more
// more
}
{
Using configuration "copyright": {
"year": "2015",
public class Startup
{
"company": "Foo Industries"
IConfiguration _configuration; }
}
public Startup()
{
_configuration = new ConfigurationBuilder()
...
.Build();
}
{
"dependencies": {
"Microsoft.AspNetCore.Mvc": "1.0.0-rc2-*",
"Microsoft.AspNetCore.Server.Kestrel": "1.0.0-rc2-*"
}
}
Middleware
• MVC is configured as middleware
• In ConfigureServices via AddMvc
• In Configure via UseMvc
public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
}
routes.MapRoute("new_default",
"{controller=Home}/{action=Index}/{id?}");
});
}
Controllers
• Controller base class still provided
• Action results now implement IActionResult
• Controller base provides many helpers to create action results
• View(), PartialView(), Content(), Json(), Ok(), Created(), HttpNotFound(),
HttpUnauthorized(), HttpBadRequest(), File(), PhysicalFile(), Redirect(),
RedirectPermanent()
[Route("[controller]/[action]")]
public class HomeController : Controller
{
// ~/Home/Index
public IActionResult Index()
{
return View();
}
}
Combining Route attributes
• Route attributes inherit path [Route("[controller]")]
public class HomeController : Controller
• RoutePrefix from MVC 5 {
// ~/Home/hello
removed [Route("hello")]
public IActionResult Index()
• Can replace inherited path {
• If template starts with "/" or }
return View();
"~/"
// ~/hello
[Route("/hello")]
public IActionResult Index2()
{
return View();
}
}
Route parameters
• [Route] allows parameters [Route("[controller]/[action]")]
public class HomeController : Controller
• With {param} syntax {
// GET ~/Home/Index
• Supports filters public IActionResult Index()
{
• With {param:filter} syntax return View();
}
// GET ~/Home/Index/5
[Route("{id:int}")]
public IActionResult Index(int id)
{
return View();
}
}
HTTP method based routes
• HttpGet, HttpPost, [Route("[controller]/[action]")]
public class HomeController : Controller
HttpPut, HttpDelete, {
HttpPatch // GET ~/Home/Index
[HttpGet]
• Filter action method public IActionResult Index()
{
on request method return View();
• Build on [Route] }
semantics // ~/Submit
[HttpPost("/Submit")]
public IActionResult Submit()
{
return View();
}
}
Areas
• Areas defined with the [Area] attribute
• Used to match an {area} route param
• Attribute routing allows [area] route token
• Views must still reside under ~/Areas/<area>/Views/<controller>
[Area("account")]
public class HomeController : Controller
public void Configure(IApplicationBuilder app) {
{ // ...
app.UseMvc(routes => }
{
routes.MapRoute("new_default",
"{area}/{controller=Home}/{action=Index}/{id?}");
});
}
POCO controllers
• Controller classes can be POCO
• Discovered in projects that reference Microsoft.AspNetCore.Mvc.*
• Identified by "Controller" class name suffix
• [NonController] disables
Dependency injection
public class HomeController
• Can inject dependencies {
into controller ctor IHttpContextAccessor _accessor;
@using Microsoft.Framework.OptionsModel
@inject IOptions<MyConfig> Config
<h2>@Config.Options.SiteName</h2>
Tag helpers
• Like custom controls for MVC
• Allow server-side code to inspect the element
• Can modify attributes, tag, and/or contents
• @addTagHelper Namespace.ClassName, Assembly
• Or @addTagHelper *, Assembly
<environment names="Staging,Production">
<h1>You're in production!</h1>
</environment>
<link rel="stylesheet"
href="//ajax.aspnetcdn.com/ajax/bootstrap/3.0.0/css/bootstrap.min.css"
asp-fallback-href="~/lib/bootstrap/css/bootstrap.min.css"
asp-fallback-test-class="hidden"
asp-fallback-test-property="visibility"
asp-fallback-test-value="hidden" />
<script src="//ajax.aspnetcdn.com/ajax/jquery.validation/1.11.1/jquery.validate.min.js"
asp-fallback-src="~/lib/jquery-validation/jquery.validate.js"
asp-fallback-test="window.jquery && window.jquery.validator">
</script>
Validation tag helpers
<form asp-controller="Account" asp-action="ForgotPassword" method="post>
<h4>Enter your email.</h4>
<div>
<label asp-for="Email"></label>
<input asp-for="Email" class="form-control" />
<span asp-validation-for="Email" class="text-danger"></span>
</div>
</form>
View components
• Replacement for child actions
• Partial views still exist
• Allow for a partial view that runs controller-like code
• Supports dependency injection
@Component.Invoke("Menu", 3)
Or
@await Component.InvokeAsync("Menu", 3)
View components
• ViewComponent base class public class MenuViewComponent : ViewComponent
{
• Matched by class prefix ICustomMenuService _menu;
// ...
}
IResourceFilter
• Surrounds model binding, action, and result (including those filters)
public interface IResourceFilter : IFilter
{
void OnResourceExecuting(ResourceExecutingContext context);
void OnResourceExecuted(ResourceExecutedContext context);
}
• ResourceExecutingContext
• Value providers, model binders, input formatters, validation providers
• Can alter these on each request
Async filters
• All filters now have IAsync<Filter> support
• Authorization, Resource, Action, Result, Exception
• Pattern similar to middleware pipeline
routes.MapRoute("formatted",
"api/{controller}.{format}");
});
}
[Produces] & [Consumes] attributes
• Used to control what formatters used on request/response
[HttpGet]
[Consumes("application/xml")]
[Produces("application/json"")]
public object Get()
{
return new {...};
}
XML compatibility shim
• Library to help migrate from Web API to Core MVC
• Microsoft.AspNetCore.Mvc.WebApiCompatShim
• Provides old classes that map to the new framework
• ApiController
• FromUriAttribute
• HttpRequestMessage helpers/extensions/model binder
• HttpResponseMessage helpers/extensions/formatter
• HttpResponseException
• HttpError
Error handling
• HandleError from MVC 5 has been removed
• Resource filter's post processing runs after exception filters
• Last chance place to "handle" exceptions with a result
• Or just can log exceptions
Error pages
• Diagnostics middleware
• Microsoft.AspNetCore.Diagnostics
• UseDeveloperExceptionPage useful for development/debugging error info
• UseExceptionHandler useful for production error pages
• Logs error information
• Invokes error path
Summary
• Brave new (yet somewhat familiar) world
• .NET Core is a cross-platform framework
• ASP.NET Core is a flexible HTTP pipeline architecture
• MVC and Web API have had a quite a make over