[ACCEPTED]-Returning plain text or other arbitary file in ASP.net-web-applications

Accepted answer
Score: 19

You should use Response property of Page 1 class:

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

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

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

This 2 removes the added overhead of a normal aspx 1 page.

Score: 4

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

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

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

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

0

Score: 0

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

More Related questions