使用 HttpListener 获取 .net 中传入数据的格式

发布于 2024-09-19 18:31:24 字数 571 浏览 3 评论 0原文

我正在编写一个服务器端程序。 我创建了一个 HttpListener 来监听传入的请求。 我怎样才能知道正在发送什么类型的数据?例如,它是文本、图像、pdf、word?

如果我的代码有误,请更正下面的代码。 我对此很陌生,我对 HTTP 概念的理解可能是错误的。谢谢。

main()
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://192.168.1.2/");
listener.Start();

while (true) //Keep on listening
{
context = listener.GetContext();
HttpListenerRequest request = context.Request;

//Do I get the request stream here, and do something with the stream to find out what data format is being sent?
Stream requestStream = request.InputStream;
}

}

I am writing a server-side program.
I created a HttpListener to listen for incoming requests.
How can I find out what kind of data is being sent in? E.g. is it a text, image, pdf, word?

Pls correct my code below if it is wrong.
I'm really new to this and my understanding of the HTTP concepts may be wrong. Thanks.

main()
{
HttpListener listener = new HttpListener();
listener.Prefixes.Add("http://192.168.1.2/");
listener.Start();

while (true) //Keep on listening
{
context = listener.GetContext();
HttpListenerRequest request = context.Request;

//Do I get the request stream here, and do something with the stream to find out what data format is being sent?
Stream requestStream = request.InputStream;
}

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

深海蓝天 2024-09-26 18:31:24

了解正在发送的数据类型的唯一简单方法是查看请求的 Content-Type 标头(通过 ContentType 属性公开),该标头应包含 MIME内容类型:

switch(request.ContentType)
{
    case "image/png":
    case "image/jpeg":
    case "image/bmp":
    case "image/gif":
    case "image/tiff":
        // OK, this is an image
        ...
        break;
    default:
        // Something else
        ...
        break;
}

请注意,这种方法并不总是有效,因为客户端可以在不指定 Content-Type 标头的情况下发送请求,或者发送与标头不匹配的数据...

The only easy way to know what type of data is being sent is by looking at the request's Content-Type header (exposed via the ContentType property), which should contain the MIME type of the content:

switch(request.ContentType)
{
    case "image/png":
    case "image/jpeg":
    case "image/bmp":
    case "image/gif":
    case "image/tiff":
        // OK, this is an image
        ...
        break;
    default:
        // Something else
        ...
        break;
}

Note that this approach won't always work, because the client could send a request without specifying the Content-Type header, or send data that doesn't match the header...

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文