ASP.NET Core MVC, action methods often return different types of results: views (HTML), JSON data, or file streams. The ContentResult class caters to a specific need: returning raw content directly to the client, without the overhead of rendering a full view. This content could be plain text, XML, JSON, CSV, or any other format you specify.
The ContentResult class provides the following key properties to shape your response: Content: This is where you set the actual content that you want to send back to the client. It could be a simple string, a serialized object, or any data you want to transmit. ContentType: This property is crucial. It specifies the MIME type (Multipurpose Internet Mail Extensions) of the content. The MIME type tells the client how to interpret the data you are sending. Here are some common examples: text/plain: Plain text text/html: HTML content application/json: JSON data text/csv: CSV data application/xml: XML data StatusCode (Optional): You can optionally set the HTTP status code of the response (e.g., 200 OK, 404 Not Found). If not specified, it defaults to 200 OK.
Creating a ContentResult You have a couple of options for creating a ContentResult in your action methods: Instantiating ContentResult: return new ContentResult() { Content = “Hello from Index”, ContentType = “text/plain” };
Using the Content() Helper Method: return Content(“Hello from Index”, “text/plain”); The Content() method is a shortcut provided by the Controller base class to conveniently create a ContentResult.
Code // HomeController.cs (modified) [Route(“home”)] [Route(“/”)] public ContentResult Index() { return Content(“<h1>Welcome</h1> <h2>Hello from Index</h2>”, “text/html”); }
In this modified Index action: HTML Content: The content being returned is an HTML string containing heading tags. Content Type: The ContentType is set to “text/html”, instructing the browser to render the response as HTML. Client Experience: When a user navigates to the /home or / route, they will see a webpage with a formatted heading “Welcome” and a subheading “Hello from Index.”