【问题标题】:Returning plain text or other arbitary file in ASP.net在 ASP.net 中返回纯文本或其他任意文件
【发布时间】:2011-07-01 23:29:43
【问题描述】:

如果我用 PHP 中的纯文本响应 http 请求,我会这样做:

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

我将如何在 ASP.NET 中做同样的事情?

【问题讨论】:

    标签: asp.net http web-applications


    【解决方案1】:

    如果您只想返回这样的纯文本,我会使用 ashx 文件(VS 中的通用处理程序)。然后只需在 ProcessRequest 方法中添加您要返回的文本即可。

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

    这消除了普通 aspx 页面的额外开销。

    【讨论】:

      【解决方案2】:

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

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

      【讨论】:

      • 技术上你不需要 Response.Flush() 因为它包含在 Response.End() 方法中。
      【解决方案3】:

      C# 中的示例(对于 VB.NET,只需删除结尾 ;):

      Response.ContentType = "text/plain";
      Response.Write("This is plain text");
      

      您可能需要事先调用Response.Clear 以确保缓冲区中已经没有标题或内容。

      【讨论】:

      • 好的。所以我只会有一个空的 .aspx 页面,然后把它放在代码隐藏中?
      • @Jo-Herman Haugholt - 差不多,虽然这也可能在 aspx 上的代码块 (&lt;%%&gt;) 中
      【解决方案4】:
      Response.ContentType = "text/plain";
      Response.Write("This is plain text");
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-26
        • 1970-01-01
        • 2011-06-05
        • 2017-12-24
        • 2013-04-01
        • 2021-11-21
        • 2014-11-08
        相关资源
        最近更新 更多