我正在尝试使用 WebAPI 将图像从我的 windows phone 8 应用程序上传到 SQL 服务器数据库。我正在为图像使用模型类,它只包含属于图像所针对的项目的 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)