如何在asp .net core web api的后台服务中获取主机URL? [英] How to get host URL in the background service in asp .net core web api?

查看:18
本文介绍了如何在asp .net core web api的后台服务中获取主机URL?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 Asp .Net 核心 web api,它将运行后台服务来每天安排一些任务并发送一些邮件.在邮件中,我需要有 api 的 url.有没有什么办法可以在除了控制器之外的后台服务中获取主机 URL.

I'm having an Asp .Net core web api which will run a background service to schedule some task daily and will send some mail. In the mail I need to have the url of the api. Is there any way to get the host URL in the background services other than controllers.

推荐答案

后台服务在 Web 请求范围之外运行,因此是后台服务.这意味着没有可用的 HTTP 上下文,您可以从中获取应用程序的主机.我建议您创建一个应用程序设置,在其中为当前环境配置主机,例如appsettings.Staging.jsonappsettings.Production.json 等,并通过注入 IConfiguration 或特定选项类在您的后台服务中使用它.

Background services run outside the scope of a web request, hence background service. This means that there is no HTTP context available where you can grab the host of the application from. I suggest you create an application setting where you configure the host for the current environment, e.g. appsettings.Staging.json, appsettings.Production.json, etc and use that in your background service by injecting IConfiguration or a specific options class.

这篇关于如何在asp .net core web api的后台服务中获取主机URL?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆