【发布时间】:2018-07-02 02:59:29
【问题描述】:
我正在尝试使用 c# 中的 httpclient 类访问 cloudinary API url,这是我的代码:
[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 bad request,并且消息是未经授权的。
但是如果我尝试从浏览器或邮递员访问 cloudinary API url,那么结果是 200 ok 并且成功。
我的问题是:
- 是不是因为我的c#代码中没有使用api键?
- 是否可以在 Cloudinary URI 中添加 api 密钥,如 google maps api 中的 api 密钥参数?
更新
我已经解决了这个问题,结果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);
}
}
【问题讨论】:
标签: c# api cloudinary