.NET Core WebAPI post parameters passed when the rear end of the receiving mode
- Entity class
- dynamic dynamic type
- JObject parameters
- Single parameter (string parameter)
Post request code distal A.
$.ajax({
url: "/api/student/poststudent",
type: 'POST',
data:JSON.stringify({ name: "张三", age: 21 }),
success:function () {
},
dataType: "json",
contentType: "application/json"
});
B. receiving the rear end of parametrically
1. entity class
Entity class is a simple way to pass parameters, very high frequency.
- Adding Entity Classes
public class Student
{
public string Name { get; set; }
public int Age { get; set; }
}
- Background Processing Post request code
[HttpPost("{id}")]
public void PostStudent(Student student)
{
}
- Receive parameters results
2.dynamic dynamic type
- Background Processing Post request code
[HttpPost("{id}")]
public void PostStudent(dynamic student)
{
var name = student.name;//name大小写与前端参数一致
var age = student.age;
}
- Receive parameters results
3.JObject parameters
- Package introduced Microsoft.AspNetCore.Mvc.NewtonsoftJson
- Add Reference
using Newtonsoft.Json.Linq;
- Background Processing Post request code
[HttpPost("{id}")]
public void PostStudent(JObject student)
{
}
- Receive parameters results
4. Single parameter (string parameter)
You could send a string parameter, and a double bag in single quotes and double quotation marks in a string content!
- Unlike the above embodiment the front end of the code
$.ajax({
url: "/api/student/poststudent",
type: 'POST',
data:'"name=张三,age=21"',//这里是重点!用单引号包一个双引号,双引号里为字符串内容!
success:function () {
},
dataType: "json",
contentType: "application/json"
});
- Background Processing Post request code
[HttpPost("{id}")]
public void PostStudent([FromBody] string values)
{
}
WebApi method parameters preceded [FromBody] identifier indicating the parameter value should be obtained from the Body request, instead of from a URL. Without [FromBody] Background fail to identify the parameter value.
- Receive parameters results
Settings allow cross-domain
If there is demand for cross-domain support, allowing cross-domain settings. Add the following code in Stateup.cs.
- ConfigureServices modification method, add the following code:
//允许一个或多个来源可以跨域
services.AddCors(options =>
{
options.AddPolicy("CustomCorsPolicy", policy =>
{
// 设定允许跨域的来源,有多个可以用','隔开
policy.WithOrigins("https://localhost:5000")//只允许https://localhost:5000来源允许跨域
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials();
});
});
- Configure modification method, add the following code:
app.UseCors("CustomCorsPolicy");