简体   繁体   English

使用 HttpClient 时出现意外响应

[英]Unexpected response when using HttpClient

I've been coding a simple API with the view of getting placeholder image of a specialized site which offers this service.我一直在编写一个简单的 API 以获取提供此服务的专业站点的占位符图像。 However, when I make a request to site with correspondent path, I'm not able of getting the image displayed on screen instead I got this HTML:但是,当我向具有对应路径的站点发出请求时,我无法在屏幕上显示图像,而是得到了这个 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.

I read the official documentation all day long but up to now I haven't realized a way to get this work properly.我整天都在阅读官方文档,但到目前为止,我还没有意识到一种让这项工作正常进行的方法。

This is my code.这是我的代码。 Obs: I have used the url "https://fakeimg.pl/300X300" and the dotnet core version 3.1.302 for this sample request. Obs:我使用 url "https://fakeimg.pl/300X300" 和 dotnet 核心版本 3.1.302 来处理这个示例请求。

FakePhotoService.cs 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 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);
        }
    }
}

Startup.cs启动.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();
            });
        }
    }
}

Program.cs程序.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>();
                });
    }
}

Please let me know what I'm doing wrong.请让我知道我做错了什么。

Update your code like so:像这样更新您的代码:

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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM