Не удается установить типы MIME при использовании C# HttpListener - PullRequest
0 голосов
/ 06 августа 2020

Я создал C# HttpListener ().

В обработчике запросов я выполняю необходимое, а затем устанавливаю заголовки и тип MIME для объекта ответа. Однако браузер сообщил, что тип MIME всегда был пустым.

private void HandleWebRequest(HttpListenerContext context)
{
    string path = context.Request.Url.LocalPath.ToLowerInvariant();
    HttpListenerResponse response = context.Response;
    HttpListenerRequest request = context.Request;
        
    try
    {
        // Respond to requests here. For ex:
        byte[] displayImage = HtmlHelper.GetTextResource(path.Substring(20));
        response.ContentLength64 = displayImage.Length;
        response.OutputStream.Write(displayImage, 0, displayImage.Length);
    }
    finally
    {
        SetResponseHeaders(path, response);
        response.Close();
    }
}
private void SetResponseHeaders(path, response)
{
    ...
    response.ContentType = MediaTypeNames.Text.Plain;
    response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
    response.AddHeader("Access-Control-Allow-Methods", "GET,POST");
    response.AddHeader("Access-Control-Allow-Origin", "*");
}

1 Ответ

0 голосов
/ 06 августа 2020

Проблема заключалась в том, что я добавил заголовки и MIME-тип в конце, когда я установил Response.Close ();

Исправление состоит в том, чтобы установить заголовки в начале

private void HandleWebRequest(HttpListenerContext context)
{
    string path = context.Request.Url.LocalPath.ToLowerInvariant();
    HttpListenerResponse response = context.Response;
    HttpListenerRequest request = context.Request;

    // Set headers here
    SetResponseHeaders(path, response);
        
    try
    {
        // Respond to requests here. For ex:
        byte[] displayImage = HtmlHelper.GetTextResource(path.Substring(20));
        response.ContentLength64 = displayImage.Length;
        response.OutputStream.Write(displayImage, 0, displayImage.Length);
    }
    finally
    {
        response.Close();
    }
}
...