Simplify using the HttpContext in a razor view (#7846)

Fixes #7832
pull/7845/head
David Fowler 2018-07-27 09:14:45 -07:00 committed by Scott Addie
parent 2a0b6d8fef
commit 9eeef1cdf5
1 changed files with 3 additions and 5 deletions

View File

@ -9,7 +9,7 @@ uid: fundamentals/httpcontext
---
# Access HttpContext in ASP.NET Core
ASP.NET Core apps access the `HttpContext` through the [IHttpContextAccessor](/dotnet/api/microsoft.aspnetcore.http.ihttpcontextaccessor) interface and its default implementation [HttpContextAccessor](/dotnet/api/microsoft.aspnetcore.http.httpcontextaccessor).
ASP.NET Core apps access the `HttpContext` through the [IHttpContextAccessor](/dotnet/api/microsoft.aspnetcore.http.ihttpcontextaccessor) interface and its default implementation [HttpContextAccessor](/dotnet/api/microsoft.aspnetcore.http.httpcontextaccessor). It's only necessary to use `IHttpContextAccessor` when you need access to the `HttpContext` inside a service.
::: moniker range=">= aspnetcore-2.0"
@ -33,14 +33,12 @@ public class AboutModel : PageModel
## Use HttpContext from a Razor view
`IHttpContextAccessor` service access is provided to a Razor view via the `@inject` directive. The following example retrieves the current username in an Intranet app using Windows Authentication:
Razor views expose the `HttpContext` directly via a [RazorPage.Context](/dotnet/api/microsoft.aspnetcore.mvc.razor.razorpage.context#Microsoft_AspNetCore_Mvc_Razor_RazorPage_Context) property on the view. The following example retrieves the current username in an Intranet app using Windows Authentication:
```cshtml
@using Microsoft.AspNetCore.Http
@inject IHttpContextAccessor HttpContextAccessor
@{
var username = HttpContextAccessor.HttpContext.User.Identity.Name;
var username = Context.User.Identity.Name;
}
```