我有一个带有startup.cs服务的asp.net core 2.2项目,该服务执行异步REST GET调用返回到我的当前站点,然后将结果(使用DI的View Component)返回到razor视图。
在服务中,我想调用“ / api / sessions”而不是“ http://localhost:3433/api/sessions”。我知道如果我在剃刀页面中可以使用〜ta帮助程序来获取Web服务器的基本路径,但是如何从服务中获取它呢?
这是我的服务和相关代码。
发件人:SessionsService.cs(这是我不想要的http://localhost,而只是〜/
公共课 { public int ID {get;组; } 公共字符串Title {get;组; } 公共字符串说明{组; } }
public class SessionsService : ISessionsService
{
public async Task<List<Session>> GetSessions(int speakerId)
{
var uri = new Uri("http://localhost:50463/api/sessions");
var httpClient = new HttpClient();
var result = await httpClient.GetStringAsync(uri);
var sessions = JsonConvert.DeserializeObject<List<Session>>(result);
return sessions;
}
}
来自:startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ISessionsService, SessionsService>();
来自:index.cshtml
<vc:speaker-card speaker="@speaker" ></vc:speaker-card>
来自:SpeakerCardViewComponent.cs
{
private ISessionsService _sessionsService;
public SpeakerCardViewComponent(ISessionsService sessionsService)
{
_sessionsService = sessionsService;
}
public async Task<IViewComponentResult> InvokeAsync(
Speaker speaker)
{
var sessions = await _sessionsService.GetSessions(101);
speaker.Sessions = sessions;
return View(speaker);
}
}
柯基·拉金(Kirk larkin)建议的答案:
public async Task<List<Session>> GetSessions(int speakerId,string baseUrl)
{
var uri = new Uri($"{baseUrl}api/sessions");
var httpClient = new HttpClient();
var result = await httpClient.GetStringAsync(uri);
var sessions = JsonConvert.DeserializeObject<List<Session>>(result);
return sessions;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<ISessionsService, SessionsService>();
services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
public class SpeakerCardViewComponent : ViewComponent
{
private ISessionsService _sessionsService;
private IHttpContextAccessor _httpContextAccessor;
public SpeakerCardViewComponent(ISessionsService sessionsService, IHttpContextAccessor httpContextAccessor)
{
_sessionsService = sessionsService;
_httpContextAccessor = httpContextAccessor;
}
public async Task<IViewComponentResult> InvokeAsync(
Speaker speaker)
{
var isHttps = _httpContextAccessor.HttpContext.Request.IsHttps;
var baseUrl = isHttps ? "https://" : "http://"
+ _httpContextAccessor.HttpContext.Request.Host.Value
+ "/";
var sessions = await _sessionsService.GetSessions(speaker.SpeakerId, baseUrl);
speaker.Sessions = sessions;
return View(speaker);
}
}