Last active
July 12, 2023 12:52
-
-
Save manoj-choudhari-git/febf34c3aa82f385392f004dd4af4bf4 to your computer and use it in GitHub Desktop.
.NET Core Web API - Example of Model Binding using Attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Route("api/[controller]")] | |
[ApiController] | |
public class ValuesController : ControllerBase | |
{ | |
// id - Inferred FromRoute | |
// val - Inferred from Query string | |
[HttpGet("{id}")] | |
public string Get([FromRoute]int id, [FromQuery(Name = "value")]) | |
{ | |
return $"{id}_{val}"; | |
} | |
[HttpPost] | |
public SubjectSummary Post([FromBody] SubjectSummary summary) | |
{ | |
return summary; | |
} | |
// Combination of FromRoute + FromBody | |
// PUT api/Values/5 | |
[HttpPut("{id}")] | |
public IActionResult Put([FromRoute] int id, [FromBody] SubjectSummary summary) | |
{ | |
return Ok(new { id = id, summary = summary }); | |
} | |
// DELETE api/Values/5 | |
[HttpDelete("{id}")] | |
public void Delete(int id) | |
{ | |
} | |
// From Header | |
[HttpGet] | |
public string GetUserAgent([FromHeader(Name = "user-agent")] string userAgent) | |
{ | |
return userAgent; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment