ASP.NET Core: 从URL加载实际呈现的文本
创始人
2024-09-15 16:30:45
0

以下是一个示例解决方案,演示如何从URL加载实际呈现的文本。

  1. 创建一个名为"TextLoader"的类:
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;
    }
}
  1. 在控制器中使用"TextLoader"类:
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);
    }
}
  1. 在Startup.cs文件中配置依赖注入:
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"类注入到控制器中。

相关内容

热门资讯

分辨真假!wejoker辅助器... 分辨真假!wejoker辅助器怎么卖,pokemmo辅助工具,切实真的有挂(真实有挂)1、破解器简单...
技巧知识分享!竞技联盟透视插件... 技巧知识分享!竞技联盟透视插件,哈糖大菠萝可以开挂吗,果然真的有挂(有挂细节)亲,关键说明,透视脚本...
揭秘!hhpoker哪个俱乐部... 揭秘!hhpoker哪个俱乐部靠谱,aapoker辅助怎么用,切实存在有挂(有挂解密)1、辅助器安装...
热点推荐!wepoker钻石怎... 热点推荐!wepoker钻石怎么看底牌,wepoker有没有挂,好像存在有挂(有人有挂)所有人都在同...
重大通报!xpoker辅助助手... 重大通报!xpoker辅助助手,wepoker怎么看底牌,好像真的有挂(确实有挂)1、首先打开辅助器...
实测教程!newpoker怎么... 实测教程!newpoker怎么安装脚本,wepoker私人局俱乐部辅助,切实有挂(有挂猫腻)1、玩家...
玩家必看科普!wepoker轻... 玩家必看科普!wepoker轻量版有透视吗,德普之星有透视辅助吗,切实是真的有挂(了解有挂)玩家必看...
技术分享!wepoker透视挂... 技术分享!wepoker透视挂底牌,pokemmo辅助官网,原来是有挂(有挂细节)1、完成有辅助插件...
记者爆料!wepoker数据分... 记者爆料!wepoker数据分析工具,wepoker怎么开辅助,本来真的是有挂(证实有挂)1、上手简...
一分钟揭秘!wpk辅助器,po... 一分钟揭秘!wpk辅助器,poker master辅助,都是是有挂(讲解有挂)1、完成有辅助插件,帮...