我正在尝试使用WebAPI将我的Windows Phone 8应用程序中的图像上传到SQL Server数据库。我正在使用图像的模型类,它只包含属于图像所用项目的ID,图像名称和用于保存图像本身的字节数组。我使用WebClient对象来访问WebAPI方法。当我尝试上传图像时,它会抛出异常,如下所示。有谁知道它为什么会出错?另外,我对其他将图像存储到SQL数据库的方法持开放态度。谢谢你看看!
代码
private MemoryStream photoStream;
...
private void upload()
{
try
{
Images image = new Images();
image.ImagesBytes = photoStream.ToArray();
image.ImagesID = 3;
image.ImagesCaption = "this is a test";
string jsonData = JsonConvert.SerializeObject(image);
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
Uri uri = new Uri("http://myIP/api/Images/", UriKind.Absolute);
webClient.UploadStringCompleted += new UploadStringCompletedEventHandler(webClient_UploadStringCompleted);
webClient.UploadStringAsync(uri, "GET", jsonData);
}
catch
{
// Display the Uploaded message
tbError.Visibility = Visibility.Visible;
}
}
...
void webClient_UploadStringCompleted(object sender, UploadStringCompletedEventArgs e)
{
try
{
Images image = JsonConvert.DeserializeObject<Images>(e.Result);
}
catch (Exception ex)
{
// Display the Uploaded message
tbError.Visibility = Visibility.Visible;
}
}
异常
System.Net.ProtocolViolationException: Operation is not valid due to the current state of the object.
at System.Net.Browser.ClientHttpWebRequest.InternalBeginGetRequestStream(AsyncCallback callback, Object state)
at System.Net.Browser.ClientHttpWebRequest.BeginGetRequestStream(AsyncCallback callback, Object state)
at System.Net.WebClient.UploadBits(WebRequest request, Stream readStream, Byte[] buffer, Byte[] header, Byte[] footer, CompletionDelegate completionDelegate, AsyncOperation asyncOp)
at System.Net.WebClient.UploadDownloadBits(WebRequest request, Stream readStream, Stream writeStream, Byte[] buffer, Byte[] header, Byte[] footer, CompletionDelegate upCompletionDelegate, CompletionDelegate downCompletionDelegate, AsyncOperation asyncOp)
at System.Net.WebClient.UploadStringAsync(Uri address, String method, String data, Object userToken)
答案 0 :(得分:1)
我认为您的HTTP方法不正确。
而不是......
webClient.UploadStringAsync(uri, "GET", jsonData);
试试......
webClient.UploadStringAsync(uri, "POST", jsonData);