【发布时间】:2013-10-05 00:19:56
【问题描述】:
以下代码负责上传图片:
[HttpPost]
public async Task<HttpResponseMessage> Upload()
{
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var streamProvider = new MultipartMemoryStreamProvider();
Cloudinary cloudinary = new Cloudinary(ConfigurationManager.AppSettings.Get("CLOUDINARY_URL"));
return await Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith(t =>
{
if (t.IsFaulted || t.IsCanceled)
throw new HttpResponseException(HttpStatusCode.InternalServerError);
var content = streamProvider.Contents.FirstOrDefault().ReadAsStreamAsync();
ImageUploadParams uploadParams = new ImageUploadParams()
{
File = new CloudinaryDotNet.Actions.FileDescription(Guid.NewGuid().ToString(), content.Result)
};
ImageUploadResult uploadResult = cloudinary.Upload(uploadParams);
string url = cloudinary.Api.UrlImgUp.BuildUrl(String.Format("{0}.{1}", uploadResult.PublicId, uploadResult.Format));
return Request.CreateResponse<MediaModel>(HttpStatusCode.Created, new MediaModel { URL = url });
});
}
它通过 jquery post 请求工作。但是,在win phone 8应用程序中,下面的代码似乎没有向api发出请求:
public async Task<string> UploadImage(byte[] image)
{
var client = new HttpClient();
var content = new MultipartFormDataContent();
var imageContent = new ByteArrayContent(image);
imageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");
content.Add(imageContent, "image", string.Format("{0}.jpg", Guid.NewGuid().ToString()));
return await client.PostAsync(baseURL + "image/Upload", content).Result.Content.ReadAsStringAsync().ContinueWith(t =>
{
return t.Result;
});
}
这里有什么问题?我希望有人能告诉我httpclient的正确用法。
【问题讨论】:
-
您收到的错误信息是什么?
-
它不会抛出任何异常。应用程序无法向 api 发出请求,但其他 api 方法(例如 Get 方法)工作正常。
标签: c#-4.0 windows-phone-8 asp.net-web-api dotnet-httpclient