常用的输出方法

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.Mvc;
 6 using System.IO;
 7 
 8 
 9 public class HomeController : Controller
10 {
11     public ActionResult Index()
12     {
13         return View();
14     }
15 
16     public ActionResult Detail()
17     {
18         return View();
19     }
20     //【1】输出简单文本内容
21     public ActionResult ContentTest()
22     {
23         string content = "<h1>Welcome to ASP.NET MVC!</h1>";
24         return Content(content);
25     }
26     //【2】输出JSON字符串
27     public ActionResult JsonTest()
28     {
29         var book = new
30         {
31             bookid = 1,
32             bookName = "ASP.NET MVC动态网站开发VIP课程",
33             author = "常老师",
34             publishData = DateTime.Now
35         };
36         return Json(book, JsonRequestBehavior.AllowGet);
37     }
38     //【3】输出JavaScript文件
39     public ActionResult JavaScriptTest()
40     {
41         string js = "alert('Welcome to ASP.NET MVC!')";
42         return JavaScript(js);
43     }
44 
45     #region 跳转控制
46 
47     //【4】重定向页面跳转
48     public ActionResult RedirectTest()
49     {
50         return Redirect("/Home/Detail");
51     }
52     //【5】跳转到指定的Action(也可以到其他控制器)
53     public ActionResult RedirectToActionTest()
54     {
55         return RedirectToAction("Detail", new { id = 1, cate = "test" });
56     }
57     //【6】使用指定的路由值跳转到指定的路由
58     public ActionResult RedirectToRouteTest()
59     {
60         return RedirectToRoute(new
61         {
62             controller = "Home",
63             action = "Detail",
64             id = 1,
65             cate = "test"
66         });
67     }
68 
69     #endregion
70 
71     #region 文件输出
72 
73 
74     //【7】按文件路径输出文件
75     public ActionResult FilePathTest()
76     {
77         return File("~/Content/rain.mp3", "audio/mp3");//参数:文件名,内容类型
78     }
79     //【8】对字符串编码,并输出文件
80     public ActionResult FileContentTest()
81     {
82         string content = "Welcome to ASP.NET MVC!";
83         byte[] contents = System.Text.Encoding.UTF8.GetBytes(content);
84 
85         return File(contents, "text/plain");
86     }
87     //【9】用文件流输出文件
88     public ActionResult FileStreamTest()
89     {     
90         FileStream fs = new FileStream(
91             Server.MapPath("~/Content/控制器详解.pdf"), FileMode.Open);
92         return File(fs, "application/pdf");
93     }
94 
95     #endregion
96 }
原文地址:https://www.cnblogs.com/atlj/p/8275654.html