Skip to content

Instantly share code, notes, and snippets.

@manoj-choudhari-git
Last active July 12, 2023 12:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save manoj-choudhari-git/febf34c3aa82f385392f004dd4af4bf4 to your computer and use it in GitHub Desktop.
Save manoj-choudhari-git/febf34c3aa82f385392f004dd4af4bf4 to your computer and use it in GitHub Desktop.
.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