如何在c#中将一个类的异步方法调用到另一个类中?

时间:2016-09-26 08:55:54

标签: c# asp.net-web-api

我有一个接口,它有一个方法原型:

public interface IDataReceiver
{
  Task<HttpResponseMessage> ReceiveAsync(string id, HttpRequestMessage request);

}

我有一个继承接口的抽象类

public abstract class DataReceiver :IDataReceiver
    {

        protected DataReceiver()
        {
        }
         public abstract Task<HttpResponseMessage> ReceiveAsync(string id, HttpRequestMessage request);
         protected virtual async Task<NameValueCollection> ReadAsFormDataAsync(HttpRequestMessage request)

    {
           //code to read the html request body
    }

}

我有另一个继承 DataReceiver

的类
 public  class Reciever1 :DataReceiver
    {
        internal const string TokenParameter = "token";

        public override async Task<HttpResponseMessage> ReceiveAsync(string id, HttpRequestMessage request)
        {
            if (id == null)
            {
                throw new ArgumentNullException(id);
            }

             // Read the request entity body
             NameValueCollection data = await ReadAsFormDataAsync(request);
             string token = data[TokenParameter];
             HttpResponseMessage tstmsg = request.CreateResponse(HttpStatusCode.OK, "Success"+token);
             return tstmsg;
}
}

我有控制器类

 public class TestController : ApiController
    {
        [HttpPost]

        public  Task<HttpResponseMessage> ProcessData(string name)
        {
          retrun   ProcessWebhook(name);
        }

       private async Task<HttpResponseMessage> ProcessWebhook(string RecieverName)
        {
            //how to call the ReceiveAsync method of Reciever1  class

            return Request.CreateResponse(HttpStatusCode.OK, "Success" +" "+ RecieverName);

          }
}

我试图在 TestController 类的 ProcessWebhook 方法中调用 Reciever1 类的 ReceiveAsync 方法但是不能要做到这一点。我尝试使用 classname.methodname 方式,但它没有显示方法。

请问这个想法吗?

谢谢!

1 个答案:

答案 0 :(得分:0)

在TestController中,您需要Reciever1实例。使用new关键字创建它:var receiver = new Reciever1();如果您正在使用DependencyInjection,请从IoC容器中解析它。

要使用类名称classname.methodname调用方法,方法必须标记为static