我尝试使用c#中的httpclient
类访问cloudinary API网址,这是我的代码:
[AllowAnonymous]
[Route("GetOverlayBrochure")]
public async Task<IHttpActionResult> GetBrochure(int tourOperatorProfileId, int bookingTemplateId) {
if (!db.TourOperatorProfiles.Any(t => t.Id == tourOperatorProfileId)) {
return NotFound();
}
if(!db.BookingTemplates.Any(b => b.Id == bookingTemplateId)) {
return NotFound();
}
HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://res.cloudinary.com/touresstest");
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("image/jpeg"));
string pathAndQuery = string.Format(
"image/upload/l_{0},w_0.5,c_scale,g_south_east,y_80,x_50/{1}.jpg",
tourOperatorProfileId,
bookingTemplateId
);
HttpResponseMessage response = await client.GetAsync(pathAndQuery);
if (response.IsSuccessStatusCode) {
return Ok(response);
} else {
return BadRequest(response.ReasonPhrase);
}
}
但是在我从Postman访问GetOverlayBrochure
API之后,我得到的响应是400个错误请求,并且该消息是未经授权的。
但是如果我尝试从浏览器或邮递员访问cloudinary API网址,那么结果就是200 ok并且成功。
我的问题是:
更新
我已经解决了这个问题,结果client.BaseAddress
无法正常工作。最后我使用了WebClient
,而不是HttpClient
。我通过将代码简化为以下代码解决了这个问题:
[AllowAnonymous]
[Route("GetOverlayBrochure")]
public async Task<HttpResponseMessage> GetBrochure(int tourOperatorProfileId, int bookingTemplateId) {
if (!db.TourOperatorProfiles.Any(t => t.Id == tourOperatorProfileId)) {
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
if (!db.BookingTemplates.Any(b => b.Id == bookingTemplateId)) {
return new HttpResponseMessage(HttpStatusCode.NotFound);
}
string pathAndQuery = string.Format(
"http://res.cloudinary.com/touresstest/image/upload/l_{0},w_0.5,c_scale,g_south_east,y_80,x_50/{1}.jpg",
tourOperatorProfileId,
bookingTemplateId
);
WebClient wc = new WebClient();
try {
byte[] imageBytes = wc.DownloadData(pathAndQuery);
using (MemoryStream ms = new MemoryStream(imageBytes)) {
System.Drawing.Image overlayResult = System.Drawing.Image.FromStream(ms);
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
result.Content = new ByteArrayContent(ms.ToArray());
result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("image/jpeg");
return result;
}
} catch (Exception) {
return new HttpResponseMessage(HttpStatusCode.InternalServerError);
}
}
答案 0 :(得分:1)
使用Cloudinary传送图像(GET)时,无需使用API密钥。
由于URL无效,通常会引发错误400。 请务必仔细检查您的代码是否生成了有效的网址。
最佳, 亚基尔