您可以只使用 ContentResult
返回纯字符串:
public ActionResult Temp() {
return Content("Hi there!");
}
默认情况下,ContentResult
返回一个 text/plain
作为其 contentType。这是可重载的,因此您还可以执行以下操作:
return Content("<xml>This is poorly formatted xml.</xml>", "text/xml");
如果您知道这是该方法将返回的唯一内容,您也可以只返回字符串。例如:
public string MyActionName() {
return "Hi there!";
}
return
语句用于根据条件发送 string
或 JSON
或 View
,那么我们必须使用 Content
来返回字符串。
public ActionResult GetAjaxValue()
{
return Content("string value");
}
截至 2020 年,使用 ContentResult
仍然是提议的 above 的正确方法,但用法如下:
return new System.Web.Mvc.ContentResult
{
Content = "Hi there! ☺",
ContentType = "text/plain; charset=utf-8"
}
有两种方法可以将字符串从控制器返回到视图:
第一的
您可以只返回字符串,但它不会包含在您的 .cshtml 文件中。它只是出现在您的浏览器中的一个字符串。
第二
您可以返回一个字符串作为查看结果的模型对象。
这是执行此操作的代码示例:
public class HomeController : Controller
{
// GET: Home
// this will return just a string, not html
public string index()
{
return "URL to show";
}
public ViewResult AutoProperty()
{
string s = "this is a string ";
// name of view , object you will pass
return View("Result", s);
}
}
在视图文件中运行 AutoProperty,它会将您重定向到结果视图并将 s 代码发送到视图
<!--this will make this file accept string as it's model-->
@model string
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Result</title>
</head>
<body>
<!--this will represent the string -->
@Model
</body>
</html>
我在 http://localhost:60227/Home/AutoProperty 运行它。
public JsonResult GetAjaxValue()
{
return Json("string value", JsonRequetBehaviour.Allowget);
}
您可以只返回一个字符串,但某些 API 不喜欢它,因为响应类型不适合响应,
[Produces("text/plain")]
public string Temp() {
return Content("Hi there!");
}
这通常可以解决问题
不定期副业成功案例分享
ContentResult
在设置HttpContext.Response.ContentType
之前会if (!String.IsNullOrEmpty(ContentType))
。我在您的第一个示例中看到了text/html
,要么这是现在的默认设置,要么是HttpContext
的有根据的猜测。MediaTypeNames.Text.Plain
或MediaTypeNames.Text.Xml
这样的 .NET 框架常量,而不是字面上添加“text/plain”作为字符串。虽然它只包括一些最常用的 MIME 类型。 (docs.microsoft.com/en-us/dotnet/api/…)