问题
I'm in need of help in getting the host/domain name and port of my application.
So far, here's my sample code in my Configure
method inside the Startup.cs
:
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var url = ""; // something that will get the current host/domain and port of the running applicaiton.
RecurringJob.AddOrUpdate<ISomething>(i=>i.SomethingToExecute(url), Cron.Daily);
}
Because I need to pass the url
string to my SomethingToExecute
method
public class Something : ISomething
{
public void SomethingToExecute(string url){
...
Debug.WriteLine(url)
}
}
回答1:
According to this Github Issue and response from the ASP.NET Core team:
It's not possible. You need to read this information directly from config. The server does not read the endpoint configuration until it's ready to start the application (after Startup). Even then, that information would be inaccurate much of the time due to reverse proxy setups like IIS, Nginx, docker, etc..
回答2:
As TanvirArjel already mentioned it seems impossible. But in your case you can dynamically get host name in your code body.
(Tested in .Net Core 2.1)
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
services.AddSingleton<something>();
}
something.cs
public class something
{
public string url;
public string SomethingToExecute()
{
return url;
}
}
Controller
[ApiController]
public class HomeController : ControllerBase
{
private something _sth;
public HomeController(something sth)
{
_sth = sth;
}
[HttpGet("foo")]
public string foo()
{
_sth.url = Request.Scheme + "://" + Request.Host;
return _sth.SomethingToExecute();
}
}
回答3:
It seems impossible but alternatively, if you want to invoke the HTTP Request or a Web API using C# Code, you can use HttpClient()
What you can do is combine what @TanvirArjel said and use HttpClient()
to invoke the HTTP Request.
- Store your host name in
appsettings.json
In your
SomethingToExecute()
use something like this.private readonly IConfiguration configuration; public ISomething(IConfiguration configuration){ this.configuration = configuration; } public void SomethingToExecute(){ var httpClient = new HttpClient(); var yourHostNameAndPort = configuration["NameFromYourAppSEttingsJsonFile"]; httpClient.Get("" + yourHostNameAndPort + "...); }
I hope it helps somebody else too.
来源:https://stackoverflow.com/questions/55369411/get-the-domain-or-host-name-and-port-in-configure-of-startup-cs