HttpContext returns null in consoleapplication in .net framework

Anonymous 1 Reputation point
2022-01-20T08:09:18.297+00:00

I am working on .net framework and want to access httpcontext in service class i.e. a console application but it is showing httpcontext as null

Windows for business Windows Client for IT Pros Networking Network connectivity and file sharing
{count} votes

1 answer

Sort by: Most helpful
  1. Limitless Technology 39,916 Reputation points
    2022-01-21T10:26:52.813+00:00

    Hello AparnaKochar

    System.Web.HttpContext.Current is populated by IIS which is not present/active during unit testing. Hence null. Do not tightly couple your code to HttpContext for that very reason. Instead encapsulate that behind abstractions that can be mocked when testing in isolation.

    Bad design aside, for your specific design you are trying to access a static dependency external to the controller. If faking the controller's context as demonstrated in your current test, then access the controller's context instead of calling the static context.


    --If the reply is helpful, please Upvote and Accept as answer--

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.