首页 > 解决方案 > 使用 HttpClient 时出现意外响应

问题描述

我一直在编写一个简单的 API,以获取提供此服务的专业站点的占位符图像。但是,当我向具有对应路径的站点发出请求时,我无法将图像显示在屏幕上,而是得到了以下 HTML:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL: <a href="https://fakeimg.pl/300x300/">http://fakeimg.pl/300x300/</a>. If not click the link.

我整天都在阅读官方文档,但到目前为止,我还没有意识到一种让这项工作正常进行的方法。

这是我的代码。Obs:我为此示例请求使用了网址“https://fakeimg.pl/300X300”和 dotnet 核心版本 3.1.302。

FakePhotoService.cs

namespace FakePhotoApi
{
    public class FakePhotoService
    {
        private readonly HttpClient _httpClient;
        private readonly ILogger<FakePhotoService> _logger;

        public FakePhotoService(HttpClient httpClient, ILogger<FakePhotoService> logger)
        {
            _logger = logger;
            _httpClient = httpClient;
        }

        public HttpRequestMessage GenerateRequest(Uri uri)
        {
            return new HttpRequestMessage(HttpMethod.Get, uri);
        }

        public async Task<string> GetFakePhoto(Tuple<int, int> dimensions)
        {
            var baseUri = new Uri($"https://fakeimg.pl/{dimensions.Item1}x{dimensions.Item2}");
            var request = GenerateRequest(baseUri);
            var response = await _httpClient.SendAsync(request);
            return await response.Content.ReadAsStringAsync();
        }
    }
}

FakePhotoController.cs

namespace FakePhotoApi.Controllers
{
    [Route("[controller]")]
    [ApiController]
    public class FakePhotoController : ControllerBase
    {
        private readonly FakePhotoService _fakePhotoService;

        public FakePhotoController(FakePhotoService fakePhotoService)
        {
            _fakePhotoService = fakePhotoService;
        }
        [HttpGet("/")]
        public async Task<IActionResult> GetFakePhoto()
        {
            var result = await _fakePhotoService.GetFakePhoto(new Tuple<int, int>(300, 300));
            return Ok(result);
        }
    }
}

启动.cs

namespace FakePhotoApi
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddHttpClient<FakePhotoService>()
            .ConfigurePrimaryHttpMessageHandler(() =>
            {
                return new HttpClientHandler
                {
                    AllowAutoRedirect = true,
                    MaxAutomaticRedirections = 5
                };
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
}

程序.cs

namespace FakePhotoApi
{
    public class Program
    {
        public static void Main(string[] args)
        {
            CreateHostBuilder(args).Build().Run();
        }

        public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseStartup<Startup>();
                });
    }
}

请让我知道我做错了什么。

标签: c#asp.netasp.net-core

解决方案


像这样更新您的代码:

public HttpRequestMessage GenerateRequest(Uri uri)
{
    var msg = new HttpRequestMessage(HttpMethod.Get, uri);
    msg.Headers.Add("User-Agent", "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.89 Safari/537.36"); // or some other real browser string
    return msg;
}

推荐阅读