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?
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".
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
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
}
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly