0

我使用 ASP.NET MVC 4 创建了一个 Rest Web 服务,在我的 Web 服务中我调用了一个名为 MessageInformer 的委托程序。

public MessageRepository repository = new MessageRepository();

public HttpResponseMessage PostMessage([FromBody]CoreMessage item)
{
    bool status = repository.TransmitMessage(item);
    if (status == true)
    {
        return Request.CreateResponse<bool>(HttpStatusCode.OK, status);
    }
    else
    {
        return Request.CreateResponse<bool>(HttpStatusCode.BadRequest, status);
    }

}

public class MessageRepository : IMessageRepository
{
    public static MessageInformer Informer;

    public void SetDelegater(MessageInformer i)
    {
        Informer = i;
    }

    public bool TransmitMessage(CoreMessage item)
    {
        Informer(item);

        return true;
    }
}

当我开始运行程序时,我为委托人设置了一个值

 MessageRepository mr = new MessageRepository();
    mr.SetDelegater(informer);

它应该调用函数 New_MessageReceived 并且在调试模式下我看到委托人在声明它之后具有正确的值但是当我在启动程序后调用 Rest 客户端并且它正在进入函数 TransmitMessage(CoreMessage item) 委托人告密者是null 尽管我之前为它分配了一个值。我设置了一些断点,它永远不会在开始和 Web 请求之间进入函数或委托人,所以我不知道为什么我的委托人为空。

休息客户端

try
{
    url = "http://localhost:5089/api/message";
    method = "POST";
    string messageString = JsonConvert.SerializeObject(message);
    var request = (HttpWebRequest)WebRequest.Create(url);
    request.Method = method;
    request.ContentType = "application/json; chatset=utf-8";

    using (Stream requestStream = request.GetRequestStream())
    using (StreamWriter writer = new StreamWriter(requestStream, Encoding.UTF8))
    {
        writer.Write(messageString);
    }

    var response = request.GetResponse() as HttpWebResponse;

    if (request.HaveResponse == true && response == null)
    {
        String msg = "response was not returned or is null";
        throw new WebException(msg);
    }
    if (response.StatusCode != HttpStatusCode.OK)
    {
        String msg = "response with status: " + response.StatusCode + " " + response.StatusDescription;
        throw new WebException(msg);
    }

    // check response headers for the content type
    string contentType = response.GetResponseHeader("Content-Type");

    // get the response content
    StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
    string responseText = reader.ReadToEnd();
    reader.Close();

    Console.WriteLine("Received " + messageString);
}
catch (Exception ex)
{
    reponseAsString += "ERROR: " + ex.Message;
}
4

1 回答 1

0

这个

public MessageRepository repository = new MessageRepository();

不是那个

MessageRepository mr = new MessageRepository();
mr.SetDelegater(informer);

您应该确保存储库已正确初始化(您是否忘记将mr分配给<object>.repository?)。

于 2013-06-12T10:20:11.973 回答