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)