我正在努力在Windows Phone 8.1
內成功實施POST
操作。如何在Windows Phone 8.1上執行POST操作
PostMessage
方法執行時沒有發現任何異常。 但MessagesController
中的POST
方法永遠不會被調用。
如何爲Windows Phone 8.1
執行POST
?
的代碼如下:
internal async Task PostMessage(string text)
{
Globals.MemberId = 1;
int memberId = 2;
// server to POST to
string url = @"http://localhost:17634/api/messages";
try
{
// HTTP web request
var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "text/plain; charset=utf-8";
httpWebRequest.Method = "POST";
// Write the request Asynchronously
using (var stream = await Task.Factory.FromAsync<Stream>(httpWebRequest.BeginGetRequestStream,
httpWebRequest.EndGetRequestStream, null))
{
//create some json string
var message = new Message() { FromId = Globals.MemberId, ToId = memberId, Content = text, Timestamp = DateTime.Now };
var json = string.Format("{0}{1}", "action=", JsonConvert.SerializeObject(message));
// convert json to byte array
byte[] jsonAsBytes = Encoding.UTF8.GetBytes(json);
// Write the bytes to the stream
await stream.WriteAsync(jsonAsBytes, 0, jsonAsBytes.Length);
}
}
catch(Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
public class MessagesController : ApiController
{
public HttpResponseMessage Post(Message message)
{
throw new NotImplementedException();
}
}
public class Message
{
public int MessageId { get; set; }
public int FromId { get; set; }
public int ToId { get; set; }
public DateTime Timestamp { get; set; }
public string Content { get; set; }
}
我沒有看到在您的示例中聲明對象「讀者」的位置。隨着該行註釋,我試圖執行代碼。但是,我仍然沒有觀察到Post方法在我的控制器中執行。 –
響應對象反映了以下狀態:StatusCode:500,ReasonPhrase:'內部服務器錯誤',版本:1.1, –
我已將其更改爲'ReadAsStringAsync',以便您可以看到響應。請再次檢查答案。 –