// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using BasicWebSite.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.ModelBinding; namespace BasicWebSite { [ApiController] [Route("/contact")] public class ContactApiController : Controller { private readonly ContactsRepository _repository; public ContactApiController(ContactsRepository repository) { _repository = repository; } [HttpGet("{id}")] public ActionResult Get(int id) { var contact = _repository.GetContact(id); if (contact == null) { return NotFound(); } return contact; } [HttpPost] public ActionResult Post([FromBody] Contact contact) { _repository.Add(contact); return CreatedAtAction(nameof(Get), new { id = contact.ContactId }, contact); } [VndError] [HttpPost("PostWithVnd")] public ActionResult PostWithVnd([FromBody] Contact contact) { _repository.Add(contact); return CreatedAtAction(nameof(Get), new { id = contact.ContactId }, contact); } [HttpPost("ActionWithInferredFromBodyParameter")] public ActionResult ActionWithInferredFromBodyParameter(Contact contact) => contact; [HttpPost(nameof(ActionWithInferredFromBodyParameterAndCancellationToken))] public ActionResult ActionWithInferredFromBodyParameterAndCancellationToken(Contact contact, CancellationToken cts) => contact; [HttpPost("ActionWithInferredRouteAndQueryParameters/{name}/{id}")] public ActionResult ActionWithInferredRouteAndQueryParameter(int id, string name, string email) { return new Contact { ContactId = id, Name = name, Email = email, }; } [HttpGet("[action]")] public ActionResult ActionWithInferredEmptyPrefix([FromQuery] Contact contact) { return contact; } [HttpGet("[action]")] public ActionResult ActionWithInferredModelBinderType( [ModelBinder(typeof(TestModelBinder))] string foo) { return foo; } [HttpGet("[action]")] public ActionResult ActionWithInferredModelBinderTypeWithExplicitModelName( [ModelBinder(typeof(TestModelBinder), Name = "bar")] string foo) { return foo; } private class TestModelBinder : IModelBinder { public Task BindModelAsync(ModelBindingContext bindingContext) { var val = bindingContext.ValueProvider.GetValue(bindingContext.ModelName); if (val == null) { return Task.CompletedTask; } bindingContext.Result = ModelBindingResult.Success("From TestModelBinder: " + val); return Task.CompletedTask; } } } }