In ASP.NET, the ContentResult
class is used to return a plain string or a custom object as a response to an HTTP request. You can use it to return any content as the result of a controller action.
Here is an example of how to use ContentResult
in ASP.NET:
csharpusing System.Web.Mvc;
public class HomeController : Controller
{
public ActionResult Index()
{
string content = "Hello, world!";
return Content(content);
}
}
In this example, the Index
action of the HomeController
returns a string "Hello, world!" as the response content using the Content
method.
You can also specify the content type of the response by passing a second parameter to the Content
method, like this:
csharppublic ActionResult Index()
{
string content = "<h1>Hello, world!</h1>";
string contentType = "text/html";
return Content(content, contentType);
}
In this example, the Index
action returns an HTML string as the response content with the content type of "text/html".
You can also set the HTTP status code of the response by passing a third parameter to the Content
method, like this:
csharppublic ActionResult Index()
{
string content = "Hello, world!";
string contentType = "text/plain";
int statusCode = 200;
return Content(content, contentType, statusCode);
}
In this example, the Index
action returns a plain text string as the response content with the content type of "text/plain" and the HTTP status code of 200.
I hope this helps you understand how to use ContentResult
in ASP.NET.
Comments
Post a Comment