DotNet 学习笔记 MVC模型

本文介绍ASP.NET Core MVC中的模型绑定与验证技术,包括模型绑定属性如[BindRequired]、[FromHeader]等,以及模型验证属性如[CreditCard]、[Compare]等,并展示了如何配置依赖注入及格式化响应数据。
Model Binding

Below is a list of model binding attributes:
•[BindRequired]: This attribute adds a model state error if binding cannot occur.
•[BindNever]: Tells the model binder to never bind to this parameter.
•[FromHeader], [FromQuery], [FromRoute], [FromForm]: Use these to specify the exact binding source you want 

to apply.
•[FromServices]: This attribute uses dependency injection to bind parameters from services.
•[FromBody]: Use the configured formatters to bind data from the request body. The formatter is selected 

based on content type of the request.
•[ModelBinder]: Used to override the default model binder, binding source and name.


Model Validation

•[CreditCard]: Validates the property has a credit card format.
•[Compare]: Validates two properties in a model match.
•[EmailAddress]: Validates the property has an email format.
•[Phone]: Validates the property has a telephone format.
•[Range]: Validates the property value falls within the given range.
•[RegularExpression]: Validates that the data matches the specified regular expression.
•[Required]: Makes a property required.
•[StringLength]: Validates that a string property has at most the given maximum length.
•[Url]: Validates the property has a URL format.



services.AddMvc(options => options.MaxModelValidationErrors = 50);

Remote validation
public class User
{
    [Remote(action: "VerifyEmail", controller: "Users")]
    public string Email { get; set; }
}

[AcceptVerbs("Get", "Post")]
public IActionResult VerifyEmail(string email)
{
    if (!_userRepository.VerifyEmail(email))
    {
        return Json(data: $"Email {email} is already in use.");
    }

    return Json(data: true);
}
Formatting Response Data
// GET api/authors/version
[HttpGet("version")]
public string Version()
{
    return "Version 1.0.0";
}

// GET api/authors/ardalis
[HttpGet("{alias}")]
public Author Get(string alias)
{
    return _authorRepository.GetByAlias(alias);
}

Startup.cs
services.AddMvc(options =>
{
  options.RespectBrowserAcceptHeader = true; // false by default
}


public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
        .AddXmlSerializerFormatters();

    services.AddScoped<IAuthorRepository, AuthorRepository>();
}
OR
services.AddMvc(options =>
{
  options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
});

Forcing a Particular Format
[Produces("application/json")]
public class AuthorsController


Special Case Formatters
services.AddMvc(options =>
{
  options.OutputFormatters.RemoveType<TextOutputFormatter>();
  options.OutputFormatters.RemoveType<HttpNoContentOutputFormatter>();
});


Response Format URL Mappings
[FormatFilter]
public class ProductsController
{
  [Route("[controller]/[action]/{id}.{format?}")]
  public Product GetById(int id)

/products/GetById/5 ---The default output formatter 
/products/GetById/5.json ---The JSON formatter (if configured) 
/products/GetById/5.xml ---The XML formatter (if configured) 

 

转载于:https://www.cnblogs.com/ziranquliu/p/5870758.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值