我尝试使用REST将图像上传到WCF服务。我认为我开始理解整个“流和字节[]”的事情,所以我不会完全丢失。但由于某种原因,我没有得到我的http请求使用POST工作。什么意思错了?
WP7代码:
byte[] avatarstream;
.......................
if (NewAvatar == true)
{
System.Uri myUri = new System.Uri(App.SERVICE_URI + "/ImageUpload/" + App.CurrentUserId.ToString());
request = (HttpWebRequest)HttpWebRequest.Create(myUri);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.BeginGetRequestStream(new AsyncCallback(GetRequestStreamCallback), request);
}
.......................
private void PhotoChooserTaskCompleted(object sender, PhotoResult e)
{
if (e.TaskResult == TaskResult.OK)
{
if (e.TaskResult == TaskResult.OK)
{
//Display the photo
BitmapImage PhotoBitmap = new BitmapImage();
PhotoBitmap.SetSource(e.ChosenPhoto);
//Convert the photo to bytes
avatarstream = new byte[e.ChosenPhoto.Length];
e.ChosenPhoto.Position = 0;
e.ChosenPhoto.Read(avatarstream, 0, avatarstream.Length);
//Convert the bytes back to a bitmap
BitmapImage RestoredBitmap = new BitmapImage();
MemoryStream stream = new MemoryStream(avatarstream);
BitmapImage image = new BitmapImage();
RestoredBitmap.SetSource(stream);
imgProfile.Source = RestoredBitmap;
}
NewAvatar = true;
}
}
void GetRequestStreamCallback(IAsyncResult callbackResult)
{
request = (HttpWebRequest)callbackResult.AsyncState;
// End the stream request operation
Stream postStream = request.EndGetRequestStream(callbackResult);
// Create the post data
// string postData = "param1=value1¶m2=value2";
// byte[] byteArray = Encoding.UTF8.GetBytes(postData);
// Add the post data to the web request
postStream.Write(avatarstream, 0, avatarstream.Length);
postStream.Close();
// Start the web request
request.BeginGetResponse(new AsyncCallback(GetResponsetStreamCallback), request);
}
void GetResponsetStreamCallback(IAsyncResult callbackResult)
{
HttpWebRequest request = (HttpWebRequest)callbackResult.AsyncState;
HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
using (StreamReader httpWebStreamReader = new StreamReader(response.GetResponseStream()))
{
string result = httpWebStreamReader.ReadToEnd();
//For debug: show results
Console.WriteLine(result);
}
}
WCF代码(合同):
[OperationContract]
[WebInvoke(
Method = "POST",
UriTemplate = "/ImageUpload/{UserId}")]
void ImageUpload(string UserId, Stream ImageStream);
WCF代码(方法):
public void ImageUpload(string UserId, Stream ImageStream)
{
byte[] buffer = new byte[ImageStream.Length];
MemoryStream ms = new MemoryStream();
int bytesRead, totalBytesRead = 0;
do
{
bytesRead = ImageStream.Read(buffer, 0, buffer.Length);
totalBytesRead += bytesRead;
ms.Write(buffer, 0, bytesRead);
} while (bytesRead > 0);
using (SqlConnection conn = new SqlConnection(conStr))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand("UPDATE UserData SET Avatar=@AvatarStream WHERE UserId=@UserId", conn))
{
cmd.Parameters.AddWithValue("@AvatarStream", buffer);
cmd.Parameters.AddWithValue("@UserId", UserId);
int rows = cmd.ExecuteNonQuery();
return;
}
}
}
WCF配置:
<?xml version="1.0"?>
<configuration>
<connectionStrings>
<add name="AzureSqlServer" connectionString="*HIDDEN INFORMATION*" />
</connectionStrings>
<!-- To collect diagnostic traces, uncomment the section below or merge with existing system.diagnostics section.
To persist the traces to storage, update the DiagnosticsConnectionString setting with your storage credentials.
To avoid performance degradation, remember to disable tracing on production deployments.
<system.diagnostics>
<sharedListeners>
<add name="AzureLocalStorage" type="WCFService.AzureLocalStorageTraceListener, WCFService"/>
</sharedListeners>
<sources>
<source name="System.ServiceModel" switchValue="Verbose, ActivityTracing">
<listeners>
<add name="AzureLocalStorage"/>
</listeners>
</source>
<source name="System.ServiceModel.MessageLogging" switchValue="Verbose">
<listeners>
<add name="AzureLocalStorage"/>
</listeners>
</source>
</sources>
</system.diagnostics> -->
<system.diagnostics>
<trace>
<listeners>
<add type="Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
name="AzureDiagnostics">
<filter type="" />
</add>
</listeners>
</trace>
</system.diagnostics>
<system.web>
<caching>
<outputCacheSettings>
<outputCacheProfiles>
<add name="NoCache" duration="0" noStore="true" varyByParam="none" />
</outputCacheProfiles>
</outputCacheSettings>
</caching>
<compilation debug="true" targetFramework="4.0" />
<authentication mode="Forms">
<forms loginUrl="~/Member/LogOn" timeout="2880" />
</authentication>
<profile>
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" connectionStringName="AzureSqlServer" applicationName="Work" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</providers>
</profile>
<roleManager>
<providers>
<clear/>
<add name="AspNetSqlRoleProvider" connectionStringName="AzureSqlServer" applicationName="Work" type="System.Web.Security.SqlRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
<add name="AspNetWindowsTokenRoleProvider" applicationName="Work" type="System.Web.Security.WindowsTokenRoleProvider, System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</providers>
</roleManager>
<membership>
<providers>
<clear/>
<remove name="AspNetSqlMembershipProvider"/>
<add name="AspNetSqlMembershipProvider" type="System.Web.Security.SqlMembershipProvider" connectionStringName="AzureSqlServer" enablePasswordRetrieval="false" enablePasswordReset="true" requiresQuestionAndAnswer="false" requiresUniqueEmail="false" maxInvalidPasswordAttempts="5" minRequiredPasswordLength="6" minRequiredNonalphanumericCharacters="0" passwordAttemptWindow="10" applicationName="Work" />
</providers>
</membership>
</system.web>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="true"/>
<!-- To receive exception details in faults for debugging purposes, set the value below to true. Set to false before deployment to avoid disclosing exception information -->
<serviceDebug includeExceptionDetailInFaults="false"/>
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" aspNetCompatibilityEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"/>
</system.webServer>
</configuration>
错误:
The remote server returned an error: NotFound.
我敢打赌,客户端正在成功创建服务,但请求不起作用,这会导致NotFound错误,我觉得这个问题有点奇怪。