以下是一个示例解决方案,演示如何从URL加载实际呈现的文本。
using System.Net.Http;
using System.Threading.Tasks;
public class TextLoader
{
private readonly HttpClient _httpClient;
public TextLoader()
{
_httpClient = new HttpClient();
}
public async Task LoadTextFromUrl(string url)
{
var response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
return content;
}
}
using Microsoft.AspNetCore.Mvc;
using System.Threading.Tasks;
public class HomeController : Controller
{
private readonly TextLoader _textLoader;
public HomeController(TextLoader textLoader)
{
_textLoader = textLoader;
}
public async Task Index(string url)
{
var text = await _textLoader.LoadTextFromUrl(url);
return Content(text);
}
}
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient();
services.AddSingleton();
services.AddMvc();
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
}
以上示例中的"TextLoader"类使用HttpClient从指定的URL加载文本内容,并将其返回给控制器。控制器使用"TextLoader"类加载文本,并使用Content()方法将其呈现到浏览器上。
请注意,示例中使用了ASP.NET Core的依赖注入功能,以将"TextLoader"类注入到控制器中。