MVC控件器动作 返回类型 IActionResult
1 using Microsoft.AspNetCore.Mvc; 2 using System.Diagnostics; 3 using System.Text; 4 using TestMvcWebApplication.Models; 5 6 namespace TestMvcWebApplication.Controllers 7 { 8 public class HomeController : Controller 9 { 10 private readonly ILogger<HomeController> _logger; 11 12 public HomeController(ILogger<HomeController> logger) 13 { 14 _logger = logger; 15 } 16 17 public IActionResult Index() 18 { 19 Student student = new Student(); 20 student.Id = 1; 21 student.Name = "Test"; 22 List<Student> students = new List<Student>(); 23 students.Add(student); 24 student = new Student { Id = 2, Name = "张三" }; 25 students.Add(student); 26 return View(students); 27 } 28 29 public IActionResult Privacy() 30 { 31 return View(); 32 } 33 public IActionResult Test() 34 {//重定向 35 return RedirectToAction("Index"); 36 } 37 public IActionResult ShowJson() 38 {//返回Json数据,中文不进行编码 39 List<Student> list = new List<Student> 40 { 41 new Student { Id=1,Name="张三" }, 42 new Student { Id=2,Name="李四"}, 43 new Student { Id=3,Name="王五"}, 44 }; 45 return Ok(list); 46 } 47 public IActionResult ShowJson2() 48 {//返回Json数据,中文已编码 49 List<Student> list = new List<Student> 50 { 51 new Student { Id=1,Name="张三" }, 52 new Student { Id=2,Name="李四"}, 53 new Student { Id=3,Name="王五"}, 54 }; 55 return Json(list); 56 } 57 public IActionResult Down() 58 {//下载文件 59 using MemoryStream ms = new MemoryStream(); 60 string content = "深圳欢迎您!"; 61 ms.Write(Encoding.UTF8.GetBytes(content)); 62 return File(ms.ToArray(), "application/octet-stream", "hello.txt"); 63 } 64 public IActionResult Content() 65 {//返回文本 66 return Content("返回文本"); 67 } 68 69 [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] 70 public IActionResult Error() 71 { 72 return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); 73 } 74 } 75 public class Student 76 { 77 public int Id { get; set; } 78 public string Name { get; set; } 79 } 80 }