How to check if I am using localhost server or not in C# MVC?

I am trying to create a background job using hangfire as explained in this article "Background jobs in ASP.NET MVC C# using" but I don't want to run this background jobs when working locally.

So, How can I check if I am on localhost in C# & ASP.NET MVC and not run this background jobs?

Asked by:- neena
: 9624 At:- 12/6/2019 12:26:06 PM
C# check if i am on localhost

2 Answers
profileImage Answered by:- manish

You can simply use the below code to check if you are on localhost

if(HttpContext.Current.Request.IsLocal )
   //Yes you are on localhost website


//check using AbsoluteURI
var IsLocal = HttpContext.Current.Request.Url.AbsoluteUri.

I have tested the first solution which is more simpler but second one should also work where we are checking is Absolute URI starts with "localhost".

At:- 12/8/2019 2:59:11 PM

profileImage Answered by:- bhanu

Above works if you are using ASP.NET MVC, but if you are using ASP.NET Core 2.1 , you can check if it is local using below code

var callingUrl = Request.Headers["Referer"].ToString();
var isLocal = Url.IsLocalUrl(callingUrl); // return if URL is local


If you are using ASP.NET Core 3.1, you can also try the below code

if (Request.Host.Host == "localhost") {
      // do something with local URL
At:- 3/23/2021 4:05:42 PM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use