c# - 使用 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>();
});
}
}
请让我知道我做错了什么。
解决方案
像这样更新您的代码:
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;
}
推荐阅读
- django - Bitbucket 克隆到 Linux 服务器
- parsing - Haskell:尽管文件中有更多输入,但在第一个表达式后解析文件完成
- python - numpy.std 是否需要均匀的数据点间距?
- javascript - 如何确保在运行函数之前加载所有资源?
- azure - Azure 托管 API 所需的配置文件的 Azure 文件存储
- c++ - 缺少宏内的 C++ 函数;
- python - 如何计算从列表中打印特定值的次数?
- c++ - 是否可以在编译期间从文件中加载字符串?C++
- ios - Firebase Storage颤动uploadTask.onComplete使ios应用程序崩溃
- angular - 无法通过 Ionic 在本地主机上使用服务工作者