当前位置:网站首页>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 .
边栏推荐
- Setting overridesorting for canvas does not take effect
- 内部振荡器、无源晶振、有源晶振有什么区别?
- 我的NVIDIA开发者之旅-Jetson Nano 2gb教你怎么训练模型(完整的模型训练套路)
- Matplotlib_ Study01
- 杰理之wif 干扰蓝牙【篇】
- Privilege management of vivo mobile phone
- [C language] about scanf() and scanf_ Some problems of s()
- Jerry's wif interferes with Bluetooth [chapter]
- FineReport安装教程
- MATLAB的官方网站上其实有很多MATLAB的学习和使用资料(文档、视频都有不少)
猜你喜欢

洛谷_P1303 A*B Problem_高精度计算
![[C language] use of nested secondary pointer of structure](/img/59/8b61805431e152995c250f6dd08e29.png)
[C language] use of nested secondary pointer of structure
![[unity Editor Extension practice] dynamically generate UI code using TXT template](/img/20/1042829c3880039c528c63d0aa472d.png)
[unity Editor Extension practice] dynamically generate UI code using TXT template

Unity releases webgl and wakes up keyboard input on the mobile terminal inputfield

10万美元AI竞赛:寻找大模型做得“更烂”的任务
![[unity Editor Extension Foundation], editorguilayout (I)](/img/f2/42413a4135fd6181bf311b685504b2.png)
[unity Editor Extension Foundation], editorguilayout (I)

EMC RS485接口EMC电路设计方案

ASP.NET CORE Study05

KDD 2022 | graph neural network generalization framework under the paradigm of "pre training, prompting and fine tuning"

UGUI强制刷新Layout(布局)组件
随机推荐
双缓冲绘图
Jerry's SPI1 plug-in flash recording modification [part]
Unity Editor Extension Foundation, editorguilayout (III)
从SimpleKV到Redis
Setting overridesorting for canvas does not take effect
Unity load settings: application backgroundLoadingPriority
杰理之wif 干扰蓝牙【篇】
UDP RTP packet frame loss
思源官方付费同步使用指南
JNI confusion of Android Application Security
Enterprise source code confidentiality scheme sharing
Unity Editor Extension Foundation, guilayout
From simplekv to redis
Levels – 虚幻引擎场景制作「建议收藏」
Unity加载设置:Application.backgroundLoadingPriority
EMC RS485接口EMC电路设计方案
为什么CAD导出PDF没有颜色
Is there a threshold for opening futures accounts? How to open futures accounts safely on the Internet
Is tongdaxin stock software reliable? Is it safe to trade stocks on it?
Unity Editor Extension Foundation, editorguilayout (II)