在ASP.net中返回纯文本或其他任意文件

Jo-*_*olt 10 asp.net web-applications http

如果我用PHP中的纯文本响应http请求,我会做类似的事情:

<?php 
    header('Content-Type: text/plain');
    echo "This is plain text";
?>
Run Code Online (Sandbox Code Playgroud)

我如何在ASP.NET中执行等效操作?

Ric*_*ton 18

如果您只想返回纯文本,我会使用ashx文件(VS中的Generic Handler).然后只需在ProcessRequest方法中添加要返回的文本.

public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/plain";
        context.Response.Write("This is plain text");
    }
Run Code Online (Sandbox Code Playgroud)

这消除了正常aspx页面的额外开销.


tpe*_*zek 16

您应该使用Page类的Response属性:

Response.Clear();
Response.ClearHeaders();
Response.AddHeader("Content-Type", "text/plain");
Response.Write("This is plain text");
Response.End();
Run Code Online (Sandbox Code Playgroud)

  • 从技术上讲,您不需要Response.Flush(),因为它包含在Response.End()方法中。 (2认同)