NetCoreServer
NetCoreServer copied to clipboard
Setting header doesn't work
I have the following override of HttpSession.OnReceivedRequest
:
protected override void OnReceivedRequest(HttpRequest request)
{
...
HttpResponse httpResponse;
if (response?.Content == null)
{
Console.WriteLine("Unrecognized request. Sending 404...");
httpResponse = Response.MakeErrorResponse(404, "");
}
else if (response.StatusCode != HttpStatusCode.OK)
{
Console.WriteLine("Received error. Sending error response...");
httpResponse = Response.MakeErrorResponse((int)response.StatusCode, response.Content);
}
else
{
Console.WriteLine($"sending response to {serverRequest.Path} ...");
httpResponse = Response.MakeGetResponse(response.Content, response.ContentType);
}
httpResponse.SetHeader("Access-Control-Allow-Origin", "*");
SendResponseAsync(httpResponse);
}
But when analyzing the response using Chrome network tools, the header is not present:
Is this a bug? Or am I doing something wrong?
Please try:
protected override void OnReceivedRequest(HttpRequest request)
{
// Prepare the response
Response.Clear();
Response.SetBegin(200);
Response.SetHeader("Access-Control-Allow-Origin", "*");
Response.SetBody();
// Send the response
SendResponseAsync(Response);
}
@chronoxor I added a bit more context to my snippet above. Is it necessary that I use the HttpSession.Response
instance of HttpResponse
rather than construction my own from - for instance - HttpSession.Response.MakeErrorResponse
?
No it's not. We use HttpSession.Response just as "always existing" object in OnReceivedRequest()
hanlder. You can create a new Response object if you like.