我使用 ASP.NET MVC 4 Web 应用程序创建了一个 Rest Webservice。如果我想使用服务并发送包含请求主体的请求,则输入参数 CoreMessage 项始终为空。我看了一些示例教程和一些示例代码,但我无法修复错误。
我的 Rest Client 的一些代码
CoreMessage message = new CoreMessage() { Source = "Dummy", Date = DateTime.Now, Data = "abcd" };
var url = "http://localhost:12294/api/message";
var method = "POST";
string reponseAsString = "";
try
{
var request = (HttpWebRequest)WebRequest.Create(url);
request.Method = method;
using (Stream requestStream = request.GetRequestStream())
using (StreamWriter writer = new StreamWriter(requestStream))
{
writer.Write(message);
}
}
catch (Exception ex)
{
reponseAsString += "ERROR: " + ex.Message;
}
我的带有 Post 功能的控制器看起来像这样
public MessageRepository repository = new MessageRepository();
public HttpResponseMessage PostMessage(CoreMessage item)
{
bool status = repository.TransmitMessage(item);
var response = Request.CreateResponse<bool>(HttpStatusCode.Created, status);
return response;
}
我的模特
public class CoreMessage
{
public string Source { get; set; }
public DateTime Date { get; set; }
public string Data { get; set; }
}