当前位置:网站首页>ASP. NET CORE Study05
ASP. NET CORE Study05
2022-06-28 12:35:00 【When the human stars shine】
Response location Set up
Example :
send out POST request , Create resources .
Notice in the request header content-type Set up , It needs to be set to application/json type , It doesn't have to be json Data of type , But by default, they all use json To transmit data , otherwise asp.net core Returns the 415 Status code .
In the simultaneous request body It must also conform to api Format required for interface , If it doesn't meet , You will get 400 Response code of .

In the response header contain location Information , Identify the location of the newly created resource .
Use Code example :
// Use here Name The attribute is Action assignment , Used to identify , General follow Action Method names are the same as
[HttpGet(template:"{CompanyId}", Name = nameof(GetCompany))]
public async Task<IActionResult> GetCompany(Guid companyId)
{
var company = await _companyRepository.GetCompanyAsync(companyId);
if (company == null)
{
return NotFound();
}
return Ok(_mapper.Map<CompanyDTO>(company));
}
// Create resources Action
[HttpPost]
public async Task<ActionResult<CompanyDTO>> CreateCompany([FromBody] CompanyAddDto company)
{
var entity = _mapper.Map<Company>(company);
_companyRepository.AddCompany(entity);
await _companyRepository.SaveAsync();
var returnDto = _mapper.Map<CompanyDTO>(entity);
// CreateRoute Method By passing Action name , And an anonymous class Used for splicing url, Information of the last response body
// The Method will be added to the response header location Information , The number It is Delivered Action Access path of add Property value set by anonymous class , By virtue of the complete url return
return CreatedAtRoute(nameof(GetCompany), new {
companyId = returnDto.Id}, returnDto);
}
ASP.NET Core Custom model binding modelbinder
In complex business logic scenarios ,asp.net core The default model binding does not meet the requirements , You need to customize it modelbinder
// Need to achieve IModelBinder Interface
public class ArrayModelBinder : IModelBinder
{
// Realization BindModelAsync Method
public Task BindModelAsync(ModelBindingContext bindingContext)
{
// Verify whether the model metadata passed in is Enumerable The type of
// If not, it returns failure
if (!bindingContext.ModelMetadata.IsEnumerableType)
{
bindingContext.Result = ModelBindingResult.Failed();
return Task.CompletedTask;
}
// Verify whether the model metadata passed in is empty
// Convert the data in the model into String type
var value = bindingContext.ValueProvider.GetValue(bindingContext.ModelName).ToString();
// Verify that the data is null, Or a blank string
if (String.IsNullOrWhiteSpace(value))
{
bindingContext.Result = ModelBindingResult.Success(null);
return Task.CompletedTask;
}
// Get the specific type of data from the model
var elementType = bindingContext.ModelType.GenericTypeArguments[0];
// Get a converter , A converter that converts a type to a specified type
var converter = TypeDescriptor.GetConverter(elementType);
// Convert the data of the model into String Data press , Division , When communicating, use the converter to String Data to Converter specified type Type data for
var values = value.Split(new[] {
"," }, StringSplitOptions.RemoveEmptyEntries).Select(x => converter.ConvertFromString(x.Trim())).ToArray();
// Create an array of the specified type and length , The value of the element of the array is the default value of the specified type
var typeValues = Array.CreateInstance(elementType, values.Length);
// Copy the converted data to the new array
values.CopyTo(typeValues, 0);
// Assign an array containing the converted data to model
bindingContext.Model = typeValues;
// Successful operation
bindingContext.Result = ModelBindingResult.Success(typeValues);
return Task.CompletedTask;
}
}
The code above will Delivered by users similar 1,2,3,4 Such a string , Through model binding , convert to IEnumable Data of type .
HTTP Options Method
1、 Get server support for HTTP Request method ;
2、 To check the performance of the server . for example :AJAX Pre check for cross domain requests , Need to send a... To another domain resource HTTP OPTIONS Request header , To determine whether the request actually sent is safe .
stay Cross domain time CORS in , Use a lot of .
Data Annotations data validation
asp.net core Built in data verification method .
stay System.ComponmentModel.DataAnnotations Namespace Attribute, For use .
IValidatableObject Interface implementation data validation
By implementing IValidatableObject Interface More complex data validation can be achieved , It can be done to Data model classes for validation , Cross attribute verification, etc .
Use :
// With the above Data Annotations Under the same namespace .
public class EmployeeAdd : IValidatableObject
{
[Display(Name = " Employee number "), Required(ErrorMessage = "{0} Are mandatory "), StringLength(10, MinimumLength = 10, ErrorMessage = "{0} Is the length of the {1}")]
public String EmployeeNo {
get; set; }
[Display(Name = " name "), Required(ErrorMessage = "{0} Are mandatory "), MaxLength(50, ErrorMessage = "{0} The maximum length of shall not exceed {1}")]
public String FirstName {
get; set; }
[Display(Name = " surname "), Required(ErrorMessage = "{0} Are mandatory "), MaxLength(50, ErrorMessage = "{0} The maximum length of shall not exceed {1}")]
public String LastName {
get; set; }
[Display(Name = " Gender ")]
public Gender Gender {
get; set; }
[Display(Name = " Date of birth ")]
public DateTime DateOfBirth {
get; set; }
// Implementation interface , Implementation method , More complex validation of classes in methods
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
{
if (FirstName == LastName)
{
yield return new ValidationResult(errorMessage: " Last name and first name cannot agree !", memberNames: new[] {
nameof(FirstName), nameof(LastName)});
}
}
}
Customize Attribute data validation
Use customization Attribute You can also perform complex data validation .
By inheritance ValidationAttribute class , And rewrite IsValid Method comes from definition Attribute.
Use
// Inherit System.ComponmentModel.DataAnnotations Under the namespace ValidationAttribute class
public class EmployeeNoMustFromFirstNameAttribute : ValidationAttribute
{
// rewrite IsValid Method
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
// Here you can complete complex validation ,
// object value yes When it's time to attribute When used on attributes You can get the specific attribute data through this parameter
// ValidationContext validationContext When used in Class time , The model class data can be obtained through this parameter
var addDto = (EmployeeAddDto)validationContext.ObjectInstance;
if (addDto.EmployeeNo == addDto.FirstName)
{
return new ValidationResult(errorMessage: " The name and number cannot be consistent ", memberNames: new[] {
nameof(EmployeeAddDto) });
}
return base.IsValid(value, validationContext);
}
}
Be careful :
In general ,asp.net core Built in data annotations The priority of verification is good ( You can simply think of it this way ), When data annotation When an error is reported during verification, the following IValidatableObject Interface and customization Attribute Will not be verified at , This is a matter of priority , and IValidatableObject Interface validation and Customize Attribute Their priorities are basically the same .
边栏推荐
- KDD 2022 | graph neural network generalization framework under the paradigm of "pre training, prompting and fine tuning"
- 【Unity编辑器扩展实践】、通过代码查找所有预制
- 攻防世界新手入门hello_pwn
- ASP.NET CORE Study08
- [vi/vim] basic usage and command summary
- 最新!基于Open3D的点云处理入门与实战教程
- 关于IP定位查询接口的测评Ⅰ
- 杰理之wif 干扰蓝牙【篇】
- What is the difference between internal oscillator, passive crystal oscillator and active crystal oscillator?
- Enterprise source code confidentiality scheme sharing
猜你喜欢

FineReport安装教程

Bytev builds a dynamic digital twin network security platform -- helping network security development

ASP.NET CORE Study01

登录接口存取token,清除token

unity发布 webgl在手机端 inputfield唤醒键盘输入

ASP.NET CORE Study02

Unity Editor Extension Foundation, GUI

Matplotlib_ Study01

智联招聘基于 Nebula Graph 的推荐实践分享

UGUI使用小技巧(六)Unity实现字符串竖行显示
随机推荐
Levels – 虚幻引擎场景制作「建议收藏」
Unity Editor Extension Foundation, GUI
Pyqt5 visual development
【Unity编辑器扩展基础】、EditorGUILayout (一)
In less than an hour, apple destroyed 15 startups
Truly understand triode beginner level chapter (Classic) "suggestions collection"
AsyncTask经验小结
2022-06-28日报:LeCun最新论文:通往自主机器智能的道路
Tips for using ugui (V) using scroll rect component
FineReport安装教程
ASP.NET CORE Study09
ASP.NET CORE Study04
From simplekv to redis
UGUI使用小技巧(六)Unity实现字符串竖行显示
MATLAB的官方网站上其实有很多MATLAB的学习和使用资料(文档、视频都有不少)
unity发布 webgl在手机端 inputfield唤醒键盘输入
【附源码+代码注释】误差状态卡尔曼滤波(error-state Kalman Filter),扩展卡尔曼滤波,实现GPS+IMU融合,EKF ESKF GPS+IMU
【Unity编辑器扩展基础】、GUILayout
ASP. NET CORE Study01
Ugui uses tips (VI) unity to realize vertical line display of string