Excerpt from https://www.cnblogs.com/ken-io/p/aspnet-core-tutorial-mvc-controller-action.html
I. Introduction
1, the main content tutorial
- ASP.NET Core MVC Controllers
- ASP.NET Core MVC Controller Operating Guide
- ASP.NET Core MVC controller action return type Introduction Introduction
- ASP.NET Core MVC controller return type operating exemplary Introduction
- ASP.NET Core MVC controller parameters mapping logic Description
- ASP.NET Core MVC controller parameter map / Get Example
2, this tutorial environmental information
Software Environment | Explanation |
---|---|
operating system | Windows 10 |
SDK | 2.1.401 |
ASP.NET Core | 2.1.3 |
HERE | Visual Studio Code 1.27 |
Browser | Chrome 69 |
Benpian the following code to adjust the code: https://github.com/ken-io/asp.net-core-tutorial/tree/master/chapter-02
3, pre-knowledge
You may need to pre-knowledge
- MVC framework / model description
https://baike.baidu.com/item/mvc
Two, ASP.NET Core MVC Controllers
1, ASP.NET Core MVC Controller Overview
In MVC Web framework, the routing module will match the received and forwarded for processing by a corresponding controller (Controller) request.
The role of the controller processing request is received, parses and executes the user input processing corresponding to the program logic, and then returns the corresponding output.
The user input may be QueryString, FormData, may be HTTP Header, HTTP Body.
The controller output format is usually: HTML, JSON, XML, plain text
2, the definition of the controller (Controller) of
All Controller classes must inherit directly or indirectly to Microsoft.AspNetCore.Mvc.ControllerBase
. In order to match the view engines, ASP.NET Core MVC framework built Microsoft.AspNetCore.Mvc.Controller
class that provides some of the features needed to view engine. So, by default we can extend this class.
3, the controller (Controller) named
Controller class class name (ClassName) recommended to the Controller
ending (not case-sensitive).
E.g:
- HomeController
- TestController
Controller routing module is removed as the end of the ControllerName.
Then the corresponding ControllerName
it were Home
, Test
. This is also the main route mapping to identify the Controller.
Of course, you can not as a controller to Controller class name (ClassName) fixed suffix, then the routing module will be fully qualified class name (ClassName) asControllerName
In ASP.NET MVC framework, the Controller (Controller) Controller to the class name as a suffix must, but this restriction is removed in ASP.NET Core MVC framework.
The following definitions Controller are possible:
//推荐
public class HomeController : Controller { //ControllerName=Home } public class HomeController : BaseController { //ControllerName=Home } public class Test : Controller { //ControllerName=Test }
Three, ASP.NET Core MVC Controller Operating Guide
1, ASP.NET Core MVC Controller Operations Overview
Controller (Controller) Operation (Action) is after the controller receives a request with the actual method of application processing request / function.
Controller After receiving the request to find a route in accordance with the corresponding ActionName Action, then map the user's input to the Action parameter, after the completion of the final actual execution of Action returns the corresponding output.
2, the controller operation (Action) is defined
Action must be public non-static methods defined in the controller, for example:
public class HomeController : Controller { public IActionResult Index() { return Content("Hello World ! -ken.io"); } public string Test() { return "test"; } public void DoSomething() { //DoSomething } }
By default routing configuration:
- Action: Index () response / home / index request
- Action: Test () response / home / test request
- Action: DoSomething () response / home / dosomething request
A public non-static method if you define the Controller, but do not want this method to process the request, it can be marked as NonAction
public class HomeController : Controller { [NonAction] public void LogicMethod(){ } }
3, the operation controller (Action) Return Type Description
ASP.NET Core MVC Action return type must be defined to achieve the Microsoft.AspNetCore.Mvc.IActionResult
type of interface, the frame itself provides a default implementation of this interface Microsoft.AspNetCore.Mvc.ActionResult
, and provides ActionResult class subclasses for different content formats required output.
However, when the method defined Action, return type can also be defined as a string, int, etc., which will return a custom type stream before returning to the response frame is suitable to automatic packaging ActionResult subtypes.
Commonly used ActionResult subclasses described
Action Return Type | Controller built-in method | Explanation |
---|---|---|
ViewResult | View() | The view of the data referred to Razor view engine rendering |
PartialViewResult | PartialView() | The view of the data referred to Razor view engine section view (PartialView) Rendering |
ContentResult | Content() | Returns the custom text |
JsonResult | Json() | Returns the serialization of the object JSON |
file Hunger | File() | Back to be written in response to the binary output |
RedirectResult | Redirect() | Redirected to the specified Url |
RedirectToRouteResult | RedirectToAction(),RedirectToRoute() | Action or redirected to the specified route |
EmptyResult | / | Will be packaged as EmptyResult return null in Action or Action define the return key is void |
Four, ASP.NET Core MVC Action exemplary method return type
1, ready to work
New in the Controllers folder ActionResultTestController.cs
and inherited from the Controller class for testing.
using System;
using Microsoft.AspNetCore.Mvc;
namespace Ken.Tutorial.Web.Controllers { public class ActionResultTestController : Controller { } }
Configuring the test controller dedicated routing Startup.cs
//配置ActionResult测试专用路由
routes.MapRoute(
name: "ActionResultTest",
template: "art/{action}", defaults: new { controller = "ActionResultTest"} );
2, ContentResult uses examples
Define the return ContentResult of Action
public IActionResult ContentTest() { return Content("Content Result Test --ken.io"); }
Startup Items, browser access {host: port} / art / contenttest, see the following output:
ContentResult Test by ken.io
3, JsonResult uses examples
Define the return JsonResult of Action
public IActionResult JsonTest() { return Json(new { Message = "JsonResult Test", Author = "ken.io" }); }
Startup Items, browser access {host: port} / art / jsontest, see the following output
{
"message": "JsonResult Test",
"author": "ken.io" }
4, FileResult uses examples
Define the return of Action FileResult
public IActionResult FileTest() { var bytes = Encoding.Default.GetBytes("FileResult Test by ken.io"); return File(bytes, "application/text", "filetest.txt"); }
Startup Items, browser access {host: port} / art / jsontest, will download files filetest.txt.
Contents of the file:
FileResult Test by ken.io
5, Redirect uses examples
Redirect the relevant definition of return Action
public IActionResult RedirectTest() { return Redirect("https://ken.io"); } public IActionResult RedirectToActionTest() { return RedirectToAction("jsontest"); } public IActionResult RedirectToRouteTest() { return RedirectToRoute("Default", new { Controller = "home", Action = "index" }); }
Start the project browser to access the test:
- Access / art / redirecttest, will jump to https://ken.io
- Access / art / redirecttoactiontest, will jump to / art / jsontest
- Access / art / redirecttoroutetest, will jump to /
Five, ASP.NET Core MVC Action method parameter mapping example
1, Action parameter map Description
Routing the request corresponding Controller process referred to, will find the corresponding Action Controller method, and from RouteData request data (QueryString, FormData, Header, etc.) or HTTP locate the value required for performing the method parameters.
If the parameter corresponding data is not found, and the parameter type is the type of null, the null value is passed as a parameter to the delivery, otherwise it will lead to a.
Additionally, Action parameter methods may not be defined, from the manual RouteData request data (QueryString, FormData, Header, etc.) or the corresponding HTTP GET parameter values.
2. Preparation
New in the Controllers folder ParamsMappingTestController.cs
and inherited from the Controller class for testing.
using System;
using Microsoft.AspNetCore.Mvc;
namespace Ken.Tutorial.Web.Controllers { public class ParamsMappingTestController:Controller { } }
Configuring the test controller dedicated routing Startup.cs
//配置参数映射测试专用路由
routes.MapRoute(
name: "ParamsMappingTest",
template: "pmt/{action}/{id?}", defaults: new { controller = "ParamsMappingTest"} );
3, an example of basic parameter map
Action Definition receives the routing parameters
public IActionResult GetId(int id) { return Content($"Action params mapping test by ken.io, id:{id}"); }
? Start the application, browser access / pmt / getid / 1024 or / pmt / getid id = 1024, will see the following output:
Action params mapping test by ken.io, id:1024
Or increase in the HTTP Header id = 1024 parameters like Tool post PostMan access / pmt / getid and sends a request, will see the same output
4, an example of a mapping array Parameter
Action Definition receiving array parameter
public IActionResult GetArray(string[] id) { var message = "Action params mapping test by ken.io,id:"; if (id != null) { message += string.Join(",", id); } return Content(message); }
? Application launch, browser access / pmt / getarray / 1,2 or / pmt / getarray id = 1,2, you will see the following output:
Action params mapping test by ken.io,id:1,2
Or the like accessible via PostMan tool post / pmt / getarray form and set the parameters and sends a request, we will see the same output
5, an example of a custom type of parameter map
Creating Models folder in the project root directory, and create a class file Person.cs
public class Person { public string Name { get; set; } public int Age { get; set; } }
Receiving a definition of a custom parameter Action
public IActionResult GetPerson(Person person) { return Json(new { Message = "Action params mapping test by ken.io", Data = person }); }
Application launch, browser access / pmt / getperson name = ken & age = 18, will see the following output?:
{
"message": "Action params mapping test by ken.io",
"data": { "name": "ken", "age": 18 } }
Or access / pmt / getperson by PostMan tool post and the like provided form the parameters and sends a request, you will see the same output
6, an array of custom types exemplary parameter mapping
Receiving a definition of a custom type of array parameter Action
public IActionResult GetPersonList(List<Person> person) { return Json(new { Message = "Action params mapping test by ken.io", Data = person }); }
Start the application, browser access /pmt/getpersonlist?person[0].name=ken&person[0].age=18&person[1].name=tom&person[1].age=20
will see the following output:
{
"message": "Action params mapping test by ken.io",
"data": [ { "name": "ken", "age": 18 }, { "name": "tom", "age": 20 } ] }
Or the like accessible via PostMan tool post / pmt / getpersonlist form and set the parameters and sends a request, we will see the same output
7, JSON type parameter mapping example
Action Definition type parameter receiving JSON
public IActionResult GetPersonJson([FromBody]Person person) { return Json(new { Message = "Action params mapping test by ken.io", Data = person }); }
Start the application, this time we can only test the tool by PostMan
First set Content-Type = application / json
JSON then set the parameters and sends a request form, you will see a corresponding output
8, exemplary parameters manually obtain
Defined parameters manually obtain Action
public IActionResult GetByHand() { return Json(new { Id = RouteData.Values["id"], Name = Request.Query["name"] }); }
? After the application starts, browser access / pmt / getbyhand / 1024 name = ken & name = tom & age = 18
will see the following output:
{
"id": "1024",
"name": [ "ken", "tom" ] }
RouteData.Values [ "id"]: acquiring data from the routing data
Request.Query [ "name"]: Get data from Url parameters
Request.Form [ "name"]: acquiring data from the form parameter