Asp.net

在 ASP.net 中返回純文字或其他任意文件

  • May 15, 2019

如果我要在 PHP 中使用純文字響應 http 請求,我會執行以下操作:

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

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

如果您只想返回這樣的純文字,我會使用 ashx 文件(VS 中的通用處理程序)。然後只需在 ProcessRequest 方法中添加您要返回的文本。

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

這消除了普通 aspx 頁面的額外成本。

您應該使用 Page 類的 Response 屬性:

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

引用自:https://stackoverflow.com/questions/5078152