Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
.NET Core Web API - Example of Model Binding using Attributes
[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