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 Hangfire.io" 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
0
: 9863 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
}

OR

//check using AbsoluteURI
var IsLocal = HttpContext.Current.Request.Url.AbsoluteUri.
            StartsWith("http://localhost:");

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".

1
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

https://docs.microsoft.com/en-us/dotnet/api/Microsoft.AspNetCore.Mvc.IUrlHelper.islocalurl?view=aspnetcore-5.0#Microsoft_AspNetCore_Mvc_IUrlHelper_IsLocalUrl_System_String_

OR

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
}
0
At:- 3/23/2021 4:05:42 PM






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

Full Name *

Email *




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