.NET Core第31天_Controller Action的各種不同回傳(ContentResult,ViewResult,RedirectResult,RedirectToActionResult,RedirectToRouteResult,FileResult)_part1
這裡一樣新增好一個專案
預設建立的專案可以看到每個action 回傳型別都為一個IActionResult的interface,每一個回傳型別都會去實作該介面,有泛型意味。
ContentResult
可以用於指定一班文字回傳或者不同MIME型態的內文
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 | using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using Net5AppDiffAction.Models; using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; namespace Net5AppDiffAction.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } public ContentResult GreetUser_GeneralStr() { return Content("Hello world from .net core mvc"); } public ContentResult GreetUser_HTML() { return Content("<div><b>Hello world from .net core mvc</b></div>","text/html"); } public ContentResult GreetUser_XML() { return Content("<div><b>Hello world from .net core mvc</b></div>", "text/xml"); } } } |
效果
最常用的
ViewResult
回傳一個畫面
1 2 3 4 5 | public ViewResult TodoList() { ViewBag.Message = "Todo List test"; return View(); } |
效果
RedirectResult
網頁跳轉
有分兩種一般跳轉(status code:302)
跟永久跳轉(status code:301)
1 2 3 4 5 6 7 8 9 | public RedirectResult GotoURL() { return Redirect("http://www.google.com"); //HTTP status code : 302 } public RedirectResult GotoURLPermanently() { return RedirectPermanent("http://www.google.com"); //HTTP status code : 301 } |
永久跳轉(status code:301)
通常若是要轉向到既有的檔案或自己站內的頁面
會建議用永久跳轉,有助於SEO成效。
如果資源已被永久刪除,將不再是先前的位置訪問。大部分Browser
都會緩存此響應並自動執行重定向,而無需再次請求原始資源。
一般跳轉(status code:302)
若想驗證回傳的status code可以下載Fiddler來自行測試
當Press Enter後即可從左側觀察的到status code回傳對應結果
RedirectToActionResult
跳轉到指定的action可傳相應的參數
1 2 3 4 5 6 7 8 9 10 | public ViewResult TodoList(string Message = "Default Message for TodoList Test") { ViewBag.Message = Message; return View(); } public RedirectToActionResult GotoContactsAction() { return RedirectToAction("TodoList", new { Message = "I am coming from a different action..." }); } |
效果
RedirectToRouteResult藉由route的跳轉
在startup.cs中做一些route的設置修改
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 | using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.HttpsPolicy; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Net5AppDiffAction { public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "TodoListRoute", pattern: "GotoAbout", defaults: new { controller = "Home", action = "TodoList" }); endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } } } |
這裡在HomeController.cs新增的這個action就是去透過指定route來做相應跳轉
1 2 3 4 | public RedirectToRouteResult GotoAbout() { return (RedirectToRoute("TodoListRoute")); } |
這裡要注意各自對應參數要一致
效果
FileResult
用於文檔下載
1 2 3 4 5 6 7 8 9 | public FileResult DownloadFile() { return File("/css/site.css","text/plain","download_newsite.css"); } public FileResult ShowLogo() { return File("./Images/logo.png","images/png"); } |
效果
Ref:
Response.Redirect() vs Response.RedirectPermanent()
Redirect() vs RedirectPermanent() in ASP.NET MVC
RedirectPermanent
留言
張貼留言