NetCoreServer icon indicating copy to clipboard operation
NetCoreServer copied to clipboard

Setting header doesn't work

Open derekantrican opened this issue 3 years ago • 4 comments

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:

image

Is this a bug? Or am I doing something wrong?

derekantrican avatar Aug 01 '21 22:08 derekantrican

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 avatar Aug 02 '21 13:08 chronoxor

@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?

derekantrican avatar Aug 02 '21 16:08 derekantrican

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.

chronoxor avatar Aug 02 '21 17:08 chronoxor