I'm implementing webserver logic using WatsonWebserver package. In request handler it might be needed to send another request to 3rd party webserver and handle a response from it. Sometimes 3rd party webserver can return bad request error with message that some parameters are missing. My webserver then send this response to the client. At this moment I want client to send me new request with missing parameters. Is it possible to communicate with client within same handler using existing HttpContextBase object in blocking mode?
using WatsonWebserver;
using WatsonWebserver.Core;
using Newtonsoft.Json.Linq;
using System.Net;
namespace GoogleAuthRequester
{
internal class Program
{
static void Main(string[] args)
{
WatsonWebserver.Core.WebserverSettings settings = new WatsonWebserver.Core.WebserverSettings("127.0.0.1", 9000, false);
WatsonWebserver.Webserver server = new WatsonWebserver.Webserver(settings, DefaultRoute);
server.Start();
Console.ReadLine();
}
static async Task DefaultRoute(HttpContextBase ctx)
{
JObject json = JObject.Parse(ctx.Request.DataAsString);
// some logic here
// sending request to 3rd party
HttpClient httpClient = new HttpClient();
using HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "https://3rdpartyservice/json/" + json);
using HttpResponseMessage response = httpClient.Send(request);
if(response.StatusCode == HttpStatusCode.BadRequest)
{
ctx.Response.StatusCode = 400;
await ctx.Response.Send(response.Content.ReadAsStringAsync().GetAwaiter().GetResult());
}
// Here I want to wait for a new request from the client with all needed parameters
// Then send these parameters to 3rd party again
}
}
}
Is it possible to get new request in the same instance of the DefaultRoute task or should I handle it in another way by generating unique id for request (context) build my logic on top of this id?
The route (in your case, the default route) isn't meant to be used in a way that keeps a persistent connection to the original caller. I would return the state back to the user (e.g.
Bad Request, status 400) along with whatever information they need to execute the request correctly.By trying to have a sort of state machine inside of a route, it would be in a way violating core principles of a RESTful architecture. Your response back to the caller upon identifying the failed request should give them the information they need to submit a new request that doesn't fail.