C# core web 控制器输出html
时间: 2024-03-06 11:46:47 浏览: 23
在C# Core Web控制器中输出HTML可以使用`ContentResult`类或`ViewResult`类。以下是两种方法的示例:
1. 使用`ContentResult`类:
```csharp
public IActionResult MyAction()
{
string html = "<html><body><h1>Hello, world!</h1></body></html>";
return new ContentResult
{
ContentType = "text/html",
StatusCode = 200,
Content = html
};
}
```
在此示例中,我们创建了一个包含HTML内容的字符串,然后使用`ContentResult`类将其返回给客户端。我们还设置了`ContentType`属性为`text/html`,以确保浏览器正确解析响应。`StatusCode`属性设置为200表示成功。
2. 使用`ViewResult`类:
```csharp
public IActionResult MyAction()
{
return View();
}
```
在此示例中,我们返回一个视图。默认情况下,视图引擎将在`Views`文件夹中查找与控制器方法同名的视图文件(例如,`MyAction.cshtml`)。如果找到视图文件,则视图引擎将使用该文件中的HTML内容作为响应。如果未找到视图文件,则会引发异常。
您可以在视图文件中编写任意的HTML代码,如下所示:
```html
<html>
<body>
<h1>Hello, world!</h1>
</body>
</html>
```
这将在浏览器中显示一个标题为“Hello, world!”的页面。