1. Foreword
The previous blog introduced ASP Net core, we have realized the access operation of the front-end interface to the background API. Unfortunately, so far, the Controller in the test code only contains a Get() method without any parameters. In the actual development process, whether it is a GET or POST request, it often contains some columns of parameters. Let's introduce how to obtain these front-end parameters in the Controller.
2. GET request mode
2.1. Build front-end interface
Generally, GET requests put parameters after URL s with "GET"? The parameters are separated by & and the general format is as follows:
http://127.0.0.1:5500/index.html?userName=admin&password=123456
Let's build a simple front-end interface. The code is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>GET request</title> <script src="jquery/jquery-3.5.1.min.js"></script> </head> <body> <button id="btn">GET pattern</button> <script> $('#btn').click(function () { $.ajax({ type: 'get', url: 'https://localhost:5001/api/Home/Get', data: { name: 'Zhang San', gender: 'male', age: 25 }, cache: false, success: function (res) { window.alert(res); }, error: function (err) { window.alert(err.status); } }); }); </script> </body> </html>
2.2 background receiving parameters
2.2.1. Foundation type and receiving parameters
The simplest method is to use the basic type parameters (string, double, int) in C # to receive. The code is as follows:
using Microsoft.AspNetCore.Mvc; namespace App.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class HomeController : ControllerBase { [HttpGet] public string Get(string name, string gender, int age) { return $"full name:{name}\n Gender:{gender}\n Age:{age}"; } } }
The running results of the program are shown in the figure below:
2.2.2 entity type receiving parameters
ASP.NET Core also allows parameters to be received through entity classes. We can define a Person class first. The code is as follows:
namespace App { public class Person { /// <summary> ///Name /// </summary> public string Name { get; set; } /// <summary> ///Gender /// </summary> public string Gender { get; set; } /// <summary> ///Age /// </summary> public int Age { get; set; } } }
Then, receive through the [FromQuery] tag in the Controller's method. The code is as follows:
using Microsoft.AspNetCore.Mvc; namespace App.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class HomeController : ControllerBase { [HttpGet] public string Get([FromQuery] Person person) { return $"full name:{person.Name}\n Gender:{person.Gender}\n Age:{person.Age}"; } } }
The running results of the program are shown in the figure below:
2.2.3 parsing JSON string receiving parameters
We can also receive parameters by parsing JSON strings. Because JavaScript provides a JSON The stringify method performs serialization, so we can pass a JSON string to the background and make the following modifications to the front-end code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>GET request</title> <script src="jquery/jquery-3.5.1.min.js"></script> </head> <body> <button id="btn">GET pattern</button> <script> $('#btn').click(function () { $.ajax({ type: 'get', url: 'https://localhost:5001/api/Home/Get', data: { json: JSON.stringify({ name: 'Zhang San', gender: 'male', age: 25 }) }, cache: false, success: function (res) { window.alert(res); }, error: function (err) { window.alert(err.status); } }); }); </script> </body> </html>
Get the string in the background and deserialize it into Person. Pay attention to the introduction of newtonsoft Jason, the code is as follows:
using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace App.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class HomeController : ControllerBase { [HttpGet] public string Get(string json) { if (string.IsNullOrEmpty(json)) { return ""; } else { Person person = JsonConvert.DeserializeObject<Person>(json); return $"full name:{person.Name}\n Gender:{person.Gender}\n Age:{person.Age}"; } } } }
The running results of the program are shown in the figure below:
3. POST request mode
3.1. Foundation type and receiving parameters
The following code is the most common POST mode request code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>POST request</title> <script src="jquery/jquery-3.5.1.min.js"></script> </head> <body> <button id="btn">POST pattern</button> <script> $('#btn').click(function () { $.ajax({ type: 'post', url: 'https://localhost:5001/api/Home/Post', data: { name: 'Zhang San', gender: 'male', age: 25 }, success: function (res) { window.alert(res); }, error: function (err) { window.alert(err.status); } }); }); </script> </body> </html>
We can try to use the basic type in the Controller to accept parameters. The code is as follows:
using Microsoft.AspNetCore.Mvc; namespace App.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class HomeController : ControllerBase { [HttpPost] public string Post(string name, string gender, int age) { return $"full name:{name}\n Gender:{gender}\n Age:{age}"; } } }
Run the program and find that the front-end parameters cannot be accepted, as shown in the following figure:
Note here: if you want to use the basic type to receive parameters in POST mode, you must label the parameters with [FromForm], and the code is as follows:
using Microsoft.AspNetCore.Mvc; namespace App.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class HomeController : ControllerBase { [HttpPost] public string Post([FromForm] string name, [FromForm] string gender, [FromForm] int age) { return $"full name:{name}\n Gender:{gender}\n Age:{age}"; } } }
The running results of the program are shown in the figure below:
3.2 entity type receiving parameters
If you want to receive parameters through the entity type, the front-end code needs to set the contentType to application/json, and the passed parameters need to use JSON The stringify method is serialized, and the code is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>POST request</title> <script src="jquery/jquery-3.5.1.min.js"></script> </head> <body> <button id="btn">POST pattern</button> <script> $('#btn').click(function () { $.ajax({ type: 'post', url: 'https://localhost:5001/api/Home/Post', contentType: 'application/json', data: JSON.stringify({ name: 'Zhang San', gender: 'male', age: 25 }), success: function (res) { window.alert(res); }, error: function (err) { window.alert(err.status); } }); }); </script> </body> </html>
In the method of Controller, you need to mark the entity class through [FromBody], and the code is as follows:
using Microsoft.AspNetCore.Mvc; namespace App.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class HomeController : ControllerBase { [HttpPost] public string Post([FromBody] Person person) { return $"full name:{person.Name}\n Gender:{person.Gender}\n Age:{person.Age}"; } } }
The running results of the program are shown in the figure below:
3.3. JObject type receiving parameters
The front-end code is as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>POST request</title> <script src="jquery/jquery-3.5.1.min.js"></script> </head> <body> <button id="btn">POST pattern</button> <script> $('#btn').click(function () { $.ajax({ type: 'post', url: 'https://localhost:5001/api/Home/Post', contentType: 'application/json', data: JSON.stringify({ name: 'Zhang San', gender: 'male', age: 25 }), success: function (res) { window.alert(res); }, error: function (err) { window.alert(err.status); } }); }); </script> </body> </html>
Personally, it is recommended to use JObject to receive parameters, because this method is more intuitive. Use NuGet to import the following components, and select version 3.1.23:
Microsoft.AspNetCore.Mvc.NewtonsoftJson
Open startup CS file, add newtonsoft The support code of Jason is as follows:
using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; namespace App { 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) { // Add newtonsoft Jason support services.AddControllers().AddNewtonsoftJson(); // Add cross domain services.AddCors(options => { options.AddPolicy("CorsPolicy", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }); }); } // 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(); } app.UseHttpsRedirection(); app.UseRouting(); app.UseAuthorization(); app.UseCors("CorsPolicy"); app.UseEndpoints(endpoints => { endpoints.MapControllers(); }); } } }
After that, we can use JObject to receive parameters. The code is as follows:
using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json.Linq; namespace App.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class HomeController : ControllerBase { [HttpPost] public string Post(JObject obj) { string name = obj["name"].ToString(); string gender = obj["gender"].ToString(); int age = int.Parse(obj["age"].ToString()); return $"full name:{name}\n Gender:{gender}\n Age:{age}"; } } }
The running results of the program are shown in the figure below:
3.4. Parse JSON string and receive parameters
We can also receive parameters by parsing JSON strings. However, the front-end code needs to be modified as follows:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>POST request</title> <script src="jquery/jquery-3.5.1.min.js"></script> </head> <body> <button id="btn">POST pattern</button> <script> $('#btn').click(function () { $.ajax({ type: 'post', url: 'https://localhost:5001/api/Home/Post', contentType: 'application/json', data: '\'' + JSON.stringify({ name: 'Zhang San', gender: 'male', age: 25 }) + '\'', success: function (res) { window.alert(res); }, error: function (err) { window.alert(err.status); } }); }); </script> </body> </html>
You can find that the above code adds two more single quotes to the data attribute. Next, you only need to parse JSON in the Controller. The code is as follows:
using Microsoft.AspNetCore.Mvc; using Newtonsoft.Json; namespace App.Controllers { [Route("api/[controller]/[action]")] [ApiController] public class HomeController : ControllerBase { [HttpPost] public string Post([FromBody] string json) { Person person = JsonConvert.DeserializeObject<Person>(json); return $"full name:{person.Name}\n Gender:{person.Gender}\n Age:{person.Age}"; } } }
The running results of the program are shown in the figure below:
4. Conclusion
This paper mainly introduces ASP Net core is a series of methods for the Controller to receive parameters in GET and POST request modes. In the actual development process, we need to select an appropriate method to receive parameters according to the scenario.