开发者

Returning plain text or other arbitary file in ASP.net

开发者 https://www.devze.com 2023-02-12 08:11 出处:网络
If I were to respond to an http request with a plain text in PHP, I would do something like: <?php

If I were to respond to an http request with a plain text in PHP, I would do something like:

<?php 
    header('Content-Type开发者_运维技巧: text/plain');
    echo "This is plain text";
?>

How would I do the equivalent in ASP.NET?


If you only want to return plain text like that I would use an ashx file (Generic Handler in VS). Then just add the text you want to return in the ProcessRequest method.

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

This removes the added overhead of a normal aspx page.


You should use Response property of Page class:

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


Example in C# (for VB.NET just remove the end ;):

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

You may want to call Response.Clear beforehand in order to ensure there are no headers or content in the buffer already.


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


and if you migrate to asp net core / blazor:

            string str = "text response";
            byte[] bytes = Encoding.ASCII.GetBytes(str);
            context.Response.ContentType = "text/plain";
            await context.Response.Body.WriteAsync(bytes, 0, bytes.Length);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号