Understanding SendAsync method ASP.net web API Message Handlers -
i trying implement custom message handler, below code.
public class myhandler : delegatinghandler { protected override async task<httpresponsemessage> sendasync(httprequestmessage request, system.threading.cancellationtoken cancellationtoken) { /* code executes while receiving request - start */ bool isbadrequest = false; if (isbadrequest) { return request.createresponse(system.net.httpstatuscode.notfound,"test"); } /* code executes while receiving request - end */ /* code executes while sending response - start */ var response = await base.sendasync(request , cancellationtoken); response.headers.add("new header", "new header value"); return response; /* code executes while sending response - end */ } }
i aware of tasks , async/await in c#. unable understand how same method gets executed both while receiving request , sending response.
this right asp.net website , explains how sendasync works.
the method takes httprequestmessage input , asynchronously returns httpresponsemessage. typical implementation following:
- process request message.
- call base.sendasync send request inner handler.
- the inner handler returns response message. (this step asynchronous.)
- process response , return caller.
here trivial example:
public class messagehandler1 : delegatinghandler { protected async override task<httpresponsemessage> sendasync( httprequestmessage request, cancellationtoken cancellationtoken) { debug.writeline("process request"); // call inner handler. var response = await base.sendasync(request, cancellationtoken); debug.writeline("process response"); return response; } }
furthermore, here great article how log request , response messages using message handler.
Comments
Post a Comment