使用 C# HttpListener 时无法设置 MIME 类型
Posted
技术标签:
【中文标题】使用 C# HttpListener 时无法设置 MIME 类型【英文标题】:Can't set MIME types when using C# HttpListener 【发布时间】:2020-11-26 03:27:17 【问题描述】:我创建了一个 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】:问题是我在设置 Response.Close(); 时在末尾添加了标头和 MIME 类型;
解决方法是在开头设置标题
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();
【讨论】:
以上是关于使用 C# HttpListener 时无法设置 MIME 类型的主要内容,如果未能解决你的问题,请参考以下文章