Dangers of using IHttpContextAccessor

Raw Coding
22 Mar 202315:44

Summary

TLDRВ этом видео Антон рассматривает проблемы, связанные с использованием IH HTTP Context Accessor в ASP.NET Core. Он объясняет, как и когда возникают эти проблемы, и как их избежать. Антон также рассматривает внутреннюю работу HTTP-контекста и дает советы, как стать лучшим инженером, имея лучшее понимание инструментов, которыми вы пользуетесь. Он также предлагает курсы по программированию на C# и приглашает заинтересованных вступить в его сервер Discord.

Takeaways

  • 😀 В видео обсуждается проблема использования IH HTTP Context Accessor и как избежать таких проблем.
  • 🛠 Рассматривается техническая сторона работы HTTP Context и того, как он появляется в приложении.
  • 🔍 Авторы стремятся повысить осведомленность инженеров о средствах, которыми они пользуются, предоставляя примеры и объяснения.
  • 💻 В видео представлены примеры кода, демонстрирующие, как может возникнуть проблема с HTTP Context Accessor.
  • 🔗 Обсуждается важность понимания того, что бизнес-логика должна существовать вне ASP.NET Core сервера.
  • 📚 Рассказывается о том, что бизнес-логика, внедряемая через контейнер внедрения зависимостей, не должна зависеть от сервисов, построенных для ASP.NET Core.
  • 🚫 Подчеркивается, что использование IHttpContextAccessor для доступа к пользователю или другому состоянию из HTTP-запроса может привести к ошибкам.
  • 🔄 Объясняется, что HTTP Context создается при начале запроса и уничтожается при его завершении, что может вызвать проблемы, если не учесть этот момент.
  • 🧩 Авторы дают советы о том, как правильно извлекать информацию из HTTP-запроса перед тем, как она будет передана в бизнес-логику.
  • 🎓 В заключении подчеркивается, что бизнес-логика должна быть разработана так, чтобы она не знала о существовании веб-сервера, чтобы избежать подобных проблем.

Q & A

  • Что такое IH HTTP Context Accessor и в чем его проблема?

    -IH HTTP Context Accessor - это сервис, который предоставляет доступ к контексту HTTP-запроса в ASP.NET Core. Проблема заключается в том, что он может быть неопределенным или иметь значение null, когда попытка доступа к нему происходит вне области запроса, что может привести к ошибкам.

  • Какие проблемы могут возникнуть при использовании IH HTTP Context Accessor?

    -Проблемы могут включать в себя исключения, связанные с доступом к null-контексту, а также проблемы с асинхронными или фоновыми операциями, которые пытаются получить доступ к информации из HTTP-контекста после завершения запроса.

  • Какое поведение демонстрирует пример с сервисом, который вызывает исключение?

    -В примере с сервисом, который вызывает исключение, функция 'somethingSlowlySync' запускает фоновую задачу, пытается получить доступ к HTTP-контексту для уведомления пользователя, но в результате получает исключение из-за отсутствия контекста.

  • Что означает термин 'async local' в контексте IH HTTP Context Accessor?

    -'Async local' - это механизм, который позволяет сохранять локальную информацию для текущего асинхронного потока выполнения. В случае с IH HTTP Context Accessor, 'async local' используется для хранения информации о HTTP-контексте для текущего запроса.

  • Какое влияние оказывает использование IH HTTP Context Accessor на архитектуру приложения?

    -Использование IH HTTP Context Accessor может привести к плохим практикам, когда бизнес-логика приложения становится зависимой от контекста HTTP, что может сделать код менее гибким и трудным для тестирования и повторного использования.

  • Как можно избежать проблем с IH HTTP Context Accessor?

    -Чтобы избежать проблем, необходимо извлекать все необходимые данные из HTTP-контекста на этапе входа в приложение и передавать их в бизнес-логику, а также избегать прямого доступа к IH HTTP Context Accessor в асинхронных или фоновых задачах.

  • Чем отличается использование IH HTTP Context Accessor в контроллерах MVC от использования в фоновых сервисах?

    -В контроллерах MVC доступ к IH HTTP Context Accessor осуществляется в контексте HTTP-запроса, и контекст доступен и актуален. В фоновых сервисах же контекст может быть недоступен или уже уничтожен, что приводит к проблемам.

  • Каковы ключевые моменты, которые нужно понимать для избегания ошибок с использованием IH HTTP Context Accessor?

    -Ключевые моменты включают понимание жизненного цикла HTTP-сервера, отделение бизнес-логики от серверной инфраструктуры, и извлечение и передача данных из HTTP-контекста в бизнес-логику перед началом обработки запроса.

  • Какие рекомендации Антон дает для работы с HTTP-контекстом в ASP.NET Core?

    -Антон рекомендует изучить концепцию HTTP-сервера, разработать бизнес-логику, которая может существовать вне ASP.NET Core, и избегать использования сервисов, построенных для ASP.NET Core, в бизнес-логике.

  • Что такое 'Default HTTP Context Factory' и как он связан с IH HTTP Context Accessor?

    -'Default HTTP Context Factory' - это сервис, который отвечает за создание и инициализацию HTTP-контекста для каждого запроса. Он связан с IH HTTP Context Accessor тем, что через него устанавливается связь между созданным HTTP-контекстом и доступом к нему через accessor.

Outlines

00:00

😀 Вступление и проблема с контекстом HTTP

Антон приветствует зрителей на своем YouTube-канале и объявляет, что сегодня будет обсуждаться проблема, связанная с доступом к контексту HTTP в ASP.NET Core. Он планирует рассмотреть, какие проблемы могут возникнуть при работе с этим и как их избежать. Также Антон предлагает углубиться в технические детали, чтобы лучше понимать, как работает HTTP-контекст. Он напоминает зрителям оставлять лайки, подписаться на канал и проверять описание видео, где располагается ссылка на курс по C#. В примере приложения с тремя конечными точками, одна из которых предназначена для отображения текущего аутентифицированного пользователя, Антон использует mock-схему аутентификации. Он обращает внимание на то, что если зрители не знакомы с аутентификацией, им стоит обратиться к предыдущим видео. В видео также рассматривается проблема с сервисом, который вызывает исключение из-за отсутствия HTTP-контекста.

05:00

😉 Проблема с доступом к HTTP-контексту в фоновых сервисах

Антон продолжает рассказ о проблеме, возникающей при попытке доступа к HTTP-контексту из фоновых сервисов. Он демонстрирует, как это может произойти, используя пример кода, в котором бизнес-логика, которая раньше работала в рамках HTTP-запроса, пытается выполниться вне этого контекста. В видео показано, что при попытке уведомления пользователя из фонового сервиса возникает исключение из-за отсутствия ссылки на HTTP-контекст. Антон подчеркивает важность понимания, что бизнес-логика должна быть независима от сервера ASP.NET Core и не должна зависеть от сервисов, предназначенных только для этого сервера, таких как HTTPContextAccessor.

10:02

🤔 Подробное объяснение работы HTTP-контекста и его доступности

В этом отрывке Антон углубляется в детали работы HTTP-контекста в ASP.NET Core. Он рассматривает процессы создания, обработки запроса и уничтожения контекста, используя классы и методы из библиотеки Castle.Core. Антон объясняет, что HTTPContextAccessor зарегистрирован в контейнере внедрения зависимостей как Singleton, но его скоуп определяется AsyncLocal, который связывает контекст с конкретным запросом. Он также демонстрирует, как и когда HTTP-контекст устанавливается и удаляется из HTTPContextAccessor, что является ключевым моментом для понимания проблемы, рассмотренной в видео.

15:03

🙂 Заключение и рекомендации для избегания проблем

Антон завершает видео с рекомендациями по избеганию подобных проблем с HTTP-контекстом. Он подчеркивает, что бизнес-логика должна быть независима от веб-сервера и не должна зависеть от сервисов, специфичных для ASP.NET Core. Антон напоминает, что все необходимые данные должны быть извлечены до входа в конечную точку или обработчик контроллера. Он также благодарит зрителей за просмотр, предлагает присоединиться к своему серверу Discord, поддержать его на Patreon и просматривает курсы по C#.

Mindmap

Keywords

💡IH HTTP контекст

IH HTTP контекст - это объект, который предоставляет информацию о текущем HTTP запросе, включая данные о клиенте, cookies, заголовки и параметры запроса. В видео это ключевой момент, так как разработчики должны быть осведомлены о том, что HTTP контекст доступен только в области запроса и не должен использоваться в фоновых сервисах, что иллюстрируется примером с(background notification service).

💡Асинхронный локальный (Async Local)

Асинхронный локальный - это механизм, позволяющий сохранять локальные данные в рамках асинхронного потока выполнения. В контексте видео, Async Local используется для хранения HTTP контекста, связанного с конкретным запросом. Это ключевая концепция для понимания, как и когда HTTP контекст доступен и как его можно использовать без ошибок.

💡Dependency Injection (DI)

Dependency Injection - это техника программирования, позволяющая компонентам приложения получать свои зависимости извне, а не создавать их самостоятельно. В видео DI используется для регистрации и внедрения различных сервисов, включая Singleton и background services, что демонстрирует, как DI в ASP.NET Core помогает строить гибкие и тестируемые приложения.

💡Background Service

Background Service - это сервис, который работает в фоновом режиме и выполняет задачи, не связанные с обработкой запросов. В видео рассматривается проблема использования HTTP контекста в таких сервисах, что приводит к ошибкам, так как HTTP контекст не существует вне области запроса.

💡Middleware

Middleware - это компонент в ASP.NET Core, который обрабатывает HTTP запросы и ответы в виде конвейера. В видео middleware упоминается в контексте обработки запроса и внедрения HTTP контекста в процесс выполнения запроса.

💡Singleton

Singleton - это шаблон проектирования, гарантирующий, что у класса есть только один экземпляр и предоставляет глобальную точку доступа к этому экземпляру. В видео Singleton используется для регистрации сервиса, который выполняет долгосрочную синхронную задачу, что демонстрирует, как Singleton может быть использован в DI контейнере.

💡Authentication

Authentication - это процесс проверки подлинности пользователя. В видео используется 'always authenticated' Authentication Handler для моделирования аутентификации, что помогает разработчикам понять, как работает аутентификация и как она взаимодействует с HTTP контекстом.

💡Hosting Abstractions

Hosting Abstractions - это уровень абстракции в ASP.NET Core, который определяет, как приложение настроено и запускается. В видео рассматривается, как приложения настраиваются и работают с HTTP контекстом через различные уровни абстракции хостинга.

💡Default HTTP Context

Default HTTP Context - это объект, который предоставляет доступ к информации о текущем HTTP запросе. В видео используется для иллюстрации того, как HTTP контекст создается и уничтожается в процессе обработки запроса.

💡HTTP Context Accessor

HTTP Context Accessor - это сервис, предоставляющий доступ к HTTP контексту. В видео рассматривается, как он зарегистрирован в качестве Singleton и как его использование может приводить к проблемам, если неправильно понимать его область видимости.

💡ASP.NET Core

ASP.NET Core - это кроссплатформенная открытая веб-платформа для создания現代化 и облачных приложений .NET. В видео ASP.NET Core используется в качестве основы для демонстрации работы с HTTP контекстом и разработки безопасных и эффективных веб-приложений.

Highlights

Anton introduces the topic of the IH HTTP context accessor and its potential issues.

Discussion on how to avoid problems related to the IH HTTP context accessor.

Explanation of the HTTP context and its lifecycle within an ASP.NET Core application.

Demonstration of a sample application with endpoints and an authentication handler.

Introduction to the concept of 'fire and forget' tasks and their impact on HTTP context.

Observation of a failed attempt to access the HTTP context outside of a request context.

Explanation of why the HTTP context is null in certain scenarios, leading to exceptions.

Illustration of how business logic should be designed to be independent of the ASP.NET Core framework.

Discussion on the importance of not relying on framework-specific services like the IH HTTP context accessor.

Presentation of a more realistic example where the same business logic is used inside and outside of an HTTP request.

Analysis of the background notification service and its interaction with the HTTP context.

Explanation of the three key concepts to avoid encountering issues with the IH HTTP context accessor.

Deep dive into the internal workings of the IH HTTP context accessor and its registration as a Singleton service.

Discussion on the role of Async Local in scoping the HTTP context to a specific request.

Inspection of the code where the HTTP context is placed into the IH HTTP context accessor.

Summary of the lifecycle of the HTTP context within the middleware pipeline.

Advice on programming business logic as if it's independent of the web server to avoid issues.

Conclusion and call to action for viewers to engage with the content and support the channel.

Transcripts

play00:00

welcome to the rocking YouTube channel

play00:01

my name is Anton and today we're going

play00:03

to be talking about the IH HTTP context

play00:05

accessor what kind of problems you can

play00:08

run into it how to avoid these problems

play00:10

we're going to be taking a look at some

play00:11

under the hood stuff of how does it work

play00:14

how does the HTTP context appear in

play00:16

there Etc basically trying to become

play00:19

better Engineers with better awareness

play00:21

of the tools that we are using don't

play00:23

forget if you're enjoying the video

play00:24

leave a like subscribe make sure to

play00:26

check out the description I have a c

play00:28

course out if you want to know c as I do

play00:31

it I highly recommend you go ahead and

play00:33

check it out with that let's go ahead

play00:34

and get started here we have the sample

play00:36

application with a couple of files

play00:38

nothing too extreme we have the program

play00:40

CS file and mainly we have three

play00:44

endpoints and this root endpoint is to

play00:47

outline the current user that is signed

play00:49

in the user that is signed in I am

play00:52

mocking an authentication schema with

play00:54

this always authenticated authentication

play00:57

Handler if you don't understand about

play00:59

Authentication you're in luck I have

play01:01

quite a few episodes on it go ahead and

play01:04

check out the description basically all

play01:06

this means is that we're always going to

play01:09

be signed in as this user you don't need

play01:11

to call login or anything like that

play01:14

amongst other services we're adding the

play01:17

ad HTTP context accessor and then we're

play01:20

registering a Singleton service some

play01:22

kind of business logic and then a

play01:25

background notification service which is

play01:27

going to be a hosted service so it's

play01:30

something that is running in the

play01:31

background if I open up the terminal the

play01:33

application is already running and if we

play01:36

just take a look at the roots we have

play01:38

this test user with the test email

play01:41

coming back to the code we're going to

play01:43

take a look at the first endpoint and

play01:45

this a service which is registered as a

play01:47

Singleton and it has a function that is

play01:49

something slowly sync now this example

play01:52

is copied from this Outline by David fer

play01:55

which explains why this service is bad

play01:59

but I don't think this example actually

play02:00

illustrates the point of how you can run

play02:03

in into this issue blindly so that's

play02:06

what we're going to be learning about

play02:07

today nevertheless first of all let's

play02:10

observe the issue this function is going

play02:12

to be a fire and forget task which we're

play02:15

going to wait for a little bit and then

play02:17

we're going to try to access the HTTP

play02:19

context and we access it by hitting the

play02:22

dummy end point and we kick off a task

play02:24

here coming back over here let's go

play02:26

ahead and kick off dummy we we have okay

play02:30

we come back if we take a look at the

play02:32

console nothing is being printed it is

play02:34

failing silently we don't actually see

play02:37

anything if we open this up and I will

play02:40

uncomment this and I will actually

play02:42

output something to the logger so we can

play02:44

actually see this failing the

play02:46

application will restart I'll come back

play02:48

over here I'll refresh and then coming

play02:51

back over here we see the explosion

play02:54

happening the reason the explosion is

play02:56

happening is the HTTP context inside the

play03:00

HTTP context accessor is null and that

play03:02

is the exception that we're getting here

play03:04

the reason it is null is because the

play03:07

HTTP context represents the HTTP context

play03:11

I don't know how else to say it other

play03:14

than when the request starts that's when

play03:17

the HTTP context is created and when the

play03:19

request ends that's when the HTTP

play03:22

context is disposed of we we'll take a

play03:24

look at the code where that actually

play03:27

happens before we do the Deep diving

play03:29

we're going to take a look at some code

play03:31

that you might write in the future that

play03:33

will essentially make you encounter this

play03:36

issue so here is some kind of service it

play03:39

is a class with a function some Services

play03:42

get injected into here and what we're

play03:44

trying to do is do something with the

play03:46

user at this point we're notifying the

play03:49

user but it can be literally anything

play03:52

the point is you're trying to access the

play03:54

user the user exists on the HTTP context

play03:57

in the MVC world the claims principle

play04:01

wasn't actually injectable so the only

play04:04

way that you can get the user is through

play04:06

the HTTP context so you would have your

play04:09

business logic rely on the ihtp context

play04:12

accessor and you would attempt to do

play04:15

something like this if we come back to

play04:17

program CS we will have the notify

play04:19

service over here we have the business

play04:21

logic and we notify the user now because

play04:24

we're awaiting over here everything is

play04:26

going to run smoothly and that is

play04:29

basically the experience that you would

play04:31

have so let's open up the terminal stuff

play04:33

is going to get restarted let's go ahead

play04:36

and notify everything is going to be

play04:39

okay and notification is successful some

play04:42

time is going to pass and what you

play04:44

actually want to have is a background

play04:47

service that is going to pull the

play04:49

database check some State and then if

play04:51

that states meet some kind of rules it

play04:54

is going to try to notify the user so

play04:56

you set up your background service you

play04:57

register it as a hosted service and then

play05:00

as you're getting a signal to notify the

play05:02

user again this can be a query to the

play05:04

database in the loop all I'm doing here

play05:07

is passing a message down a channel I'm

play05:09

then creating a scope and then I'm

play05:11

retrieving the business logic because

play05:13

that logic of notifying a user I want

play05:16

that to be reusable and then I notify

play05:18

the user if I go to program CS we have

play05:21

the background notification service over

play05:22

here and I write test into the

play05:24

background notification service so

play05:26

that's going to go into this channel

play05:27

writer over here and then this channel

play05:30

reader is going to pick up the message

play05:32

okay so that's basically how it's going

play05:33

to go into here with this example it's a

play05:37

little bit more of a realistic example

play05:40

of what is being highlighted over here

play05:42

you start off with logic that was

play05:44

running during an HTTP request and then

play05:47

you want to execute that same logic

play05:49

outside of an HTTP request and that is

play05:53

how you essentially encounter this issue

play05:55

so

play05:56

notify DBS if I open up well we'll see

play06:00

that we again encounter the N reference

play06:02

exception on the IH HTTP context

play06:04

accessor at this point if you're still

play06:06

listening the audience is pretty much

play06:08

split into two parts the first one that

play06:11

has been taught the lesson or has

play06:13

encountered this issue and learned the

play06:15

lesson or the second part that is maybe

play06:18

a little bit blind first time you hear

play06:19

about this ihtp context accessor what do

play06:22

you need to understand to not encounter

play06:24

this issue and similar issues there will

play06:27

be three things first is the concept of

play06:29

the HTTP server and that is the asp.net

play06:32

core application that you're programming

play06:34

second is the business logic this

play06:36

business logic should be able to exist

play06:39

outside of the asp.net core server

play06:42

generally what happens is you take the

play06:43

business logic and you register it with

play06:45

the dependency injection container and

play06:48

then that business logic will get

play06:50

injected into your MVC controllers or

play06:53

endpoints and at that point everything

play06:55

seems to be fused together you need to

play06:58

understand that your business logic that

play07:00

is even though it is injected through

play07:02

the dependency injection controller

play07:04

should not rely on services that are

play07:08

built for the asp.net core framework the

play07:11

ihtp context accessor is an example of a

play07:13

service which is used for the asp.net

play07:16

core framework to do HTTP web server

play07:19

things as you receive the request it's

play07:21

going to go through the middleware

play07:22

pipeline and at that point you need to

play07:24

extract all the information that you can

play07:26

get you're essentially preparing the

play07:28

scene and then you're injecting it all

play07:30

into the business logic and you're

play07:32

setting up your business logic to then

play07:34

execute so you still have your web

play07:36

server you still have your business

play07:37

logic controllers and endpoints is that

play07:41

place where you transfer from the web

play07:43

server world into your business logic

play07:46

World As Long as You Follow that rule

play07:48

you will never encounter an issue like

play07:50

this where you will spot uh this belongs

play07:53

to the web server because there is some

play07:55

awareness of HTTP RPC websockets

play07:59

whatever other web service notion there

play08:02

might be you want to take that out let's

play08:05

come back to the code and actually

play08:08

inspect what is the IH HTTP context

play08:11

accessor and how is it set so first of

play08:14

all let's unpackage add HTTP context

play08:17

accessor and here we will see the HTTP

play08:19

context accessor being registered and

play08:22

it's actually registered as a Singleton

play08:24

service so even though it exists only

play08:27

for the scope of the HT CTP request it

play08:31

itself is not a sculpt service the thing

play08:35

that actually gives the ihtp context

play08:39

accessor its scopen is this async local

play08:43

which is a pretty loaded concept and in

play08:46

order to understand how it actually

play08:48

works under the hood deserves a video of

play08:51

its own looking at this all you need to

play08:53

understand is asyn local is the thing

play08:56

that will make the HTTP context holder

play08:59

the thing that holds the HTTP context

play09:02

for this specific request that is being

play09:04

made to the server because that request

play09:06

will be executed in an async task async

play09:10

local is the thing which is going to

play09:12

scope this HTTP context to the task or

play09:15

to the async context which is going to

play09:17

be processing the request with that

play09:20

let's back out back into program Cs and

play09:23

we're going to understand at which point

play09:25

the HTTP context is actually placed into

play09:28

the I HTTP context accessor what I'm

play09:31

about to do here you can get more

play09:32

information from the castol video I did

play09:34

where we try to understand if it's worth

play09:37

building our own web framework on top of

play09:39

cro similar to asp.net core the answer

play09:42

to which is no but nevertheless we learn

play09:44

things about Castrol and how to interact

play09:46

with krol here I'm just going to show

play09:48

you how to walk down to Castrol from

play09:51

your esp. net core application let's go

play09:54

ahead and decompile run and here we'll

play09:56

have this hosting abstractions host

play09:58

extensions run and here again down to

play10:01

run a Sync here is where the web server

play10:05

Starts Here It basically just waits for

play10:07

the web server to shut down so until you

play10:09

actually shut down the server the

play10:11

execution is going to be paused here

play10:14

we're going to go into start a sync and

play10:16

this is on the interface so we want to

play10:18

go to the implementation of the host

play10:20

class in here we will go through

play10:22

execution up until we reach a loop where

play10:25

we have a bunch of hosted Services if we

play10:28

come back to program CS where I register

play10:30

the background notification service

play10:32

which is a background service which is

play10:34

still a hosted service the krol server

play10:37

is a background service which is running

play10:40

in the background and servicing your

play10:41

requests coming back to the host we have

play10:44

the hosted Services over here and start

play10:47

async is being called specifically the

play10:50

castral web server is a generic web host

play10:53

server and here again we will scroll

play10:55

down up until we have this application

play10:58

which is essenti

play10:59

the request delegate if you know what

play11:01

the request delegate your web server

play11:04

your asp.net core app is essentially

play11:06

just a configured middleware pipeline

play11:09

which will get passed down into this

play11:11

hosting application the stard a sync

play11:13

over here is called on the server so I

play11:16

server or implementations for I server

play11:19

will be the Cal server and Cal server

play11:21

internal implementation and then you can

play11:23

also have an is HTTP server okay we are

play11:27

particularly interested or not so

play11:29

interested in the actual classes but

play11:33

rather the thing that is passed down to

play11:36

the castol server so coming back over

play11:38

here we have stard a sync and HTTP

play11:40

application is being passed down into it

play11:42

we're going to go into host application

play11:45

and down here we will first have create

play11:48

context we will then have process

play11:51

request async and then dispose of

play11:53

context to summarize these three

play11:55

functions the create context is when you

play11:59

are receiving the request so you doing

play12:01

some setup you're then processing the

play12:04

request and that's going to be the

play12:06

underscore application which is again

play12:08

just your middleware pipeline and then

play12:10

you have the dispose context which is

play12:12

basically going to tear everything down

play12:15

in these contexts what is being used is

play12:18

a default HTTP context which is a

play12:20

service which is registered at the point

play12:23

of this create Builder so when you

play12:26

initially set up your Builder this

play12:29

service already exists internally and

play12:31

I've gone to bad Services over here but

play12:33

I want to be over here okay and sorry I

play12:35

wasn't talking about the default HTTP

play12:37

context is the default HTTP context

play12:39

Factory this is a service which exists

play12:42

from the beginning over here when you

play12:44

call create Builder Okay the default

play12:47

HTTP context Factory if we take a look

play12:49

at the create function that is going to

play12:52

be inside the default HTTP context

play12:54

factoring so just this class when we

play12:57

create the HTTP cont context so the

play12:59

default HTTP context over here it goes

play13:02

through an initialization process the

play13:05

default HTTP context Factory because it

play13:07

comes from the same dependency injection

play13:09

container where you're registering your

play13:11

services it is attempting to extract an

play13:14

HTTP context accessor from that same

play13:17

container and you can see that this HTTP

play13:19

context accessor if you never call add

play13:22

HTTP context accessor it is actually

play13:24

going to be null so this logic has to

play13:26

account for that fact if the service is

play13:29

present this is actually just going to

play13:31

go ahead and set the HTTP context on the

play13:34

HTTP context accessor okay so this

play13:37

answers the question of when does the

play13:40

HTTP context actually gets placed into

play13:43

the HTTP context accessor and how long

play13:46

does it actually exist there if we again

play13:49

come back to the host application during

play13:52

the setup of the request the ihtp

play13:56

context accessor service actually gets

play13:59

prepared and loaded with the created

play14:01

HTTP context over here you then place

play14:05

the HTTP context into the middleware

play14:08

pipeline so it gets processed and after

play14:11

which if we have the HTTP context

play14:13

accessor we clear it from the context

play14:15

and the dispose on the HTTP context

play14:18

Factory this is where it's actually

play14:20

going to clear it away from the HTTP

play14:23

context accessor itself now I've

play14:25

probably said HTTP context accessor like

play14:27

a gazillion times but all you need to

play14:29

know is that HTTP context accessor is

play14:32

set up and the HTTP context inside the

play14:35

HTTP context accessor gets wiped out

play14:38

before and after the HTTP context

play14:40

actually gets sent into your middleware

play14:43

with that I think it's a good time to

play14:44

end the video remember even though your

play14:46

business logic sits inside the web

play14:49

server you want to program it as if it

play14:51

doesn't know anything about the web

play14:52

server this way you're never going to

play14:54

encounter a problem like relying on the

play14:57

ihtp context access to get a user or

play15:00

some kind of other state from the HTTP

play15:02

request make sure all of that

play15:04

information is extracted before or at

play15:08

the point of you entering your endpoint

play15:10

or action or Handler on the controller

play15:13

razor page whatever it is that endpoint

play15:16

action or Handler is the transition from

play15:19

the HTTP server world into your business

play15:22

logic as always if you enjoyed the video

play15:23

don't forget to leave a like subscribe

play15:25

if you have any questions make sure to

play15:27

leave them in the comment section go

play15:28

join my Discord server and if you want

play15:30

the code for this video as well as my

play15:32

other videos come support me on Patron I

play15:34

will really appreciate it and a very

play15:35

very big thank you to all of my current

play15:37

patreon supporters you help me make

play15:38

these videos don't forget to check out

play15:40

my C course again thank you for watching

play15:43

have a good day

Rate This

5.0 / 5 (0 votes)

Related Tags
ASP.NET CoreIH HTTP ContextРазработкаПроблемыИсключенияDependency InjectionSingleton ServiceBackground ServiceHTTP ServerMiddleware
Do you need a summary in English?