Reputation: 3051
I have created the following web service and can access it by:
https://localhost:44311/valores/1
but I want to access it with a url like:
https://localhost:44311/usuario/1
using usuario
in the url
[HttpGet("{id:int}",Name ="usuario")]
public ActionResult<Usuario> Get(int id)
{
using (var db = new prueba2Context())
{
var usuario = db.Usuario.Where(x => x.Id == id).FirstOrDefault();
if (usuario == null)
{
return NotFound();
}
return Ok(usuario);
}
}
I am new to c#
, I appreciate if you indicate what I am doing wrong and how to correct it.
This is the structure of my folder.
Upvotes: 0
Views: 1584
Reputation: 13597
It looks like you are using ASP.NET Core. A typical endpoint will be set up like this:
[ApiController, Route("api/[controller]")]
public class ComputationController : ControllerBase
{
// ...
[HttpPost, Route("beginComputation")]
[ProducesResponseType(StatusCodes.Status202Accepted, Type = typeof(JobCreatedModel))]
public async Task<IActionResult> BeginComputation([FromBody] JobParametersModel obj)
{
return Accepted(
await _queuedBackgroundService.PostWorkItemAsync(obj).ConfigureAwait(false));
}
[HttpGet, Route("computationStatus/{jobId}")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(JobModel))]
[ProducesResponseType(StatusCodes.Status404NotFound, Type = typeof(string))]
public async Task<IActionResult> GetComputationResultAsync(string jobId)
{
var job = await _computationJobStatusService.GetJobAsync(jobId).ConfigureAwait(false);
if(job != null)
{
return Ok(job);
}
return NotFound($"Job with ID `{jobId}` not found");
}
// ...
}
The [ProducesResponseType]
attribute is for documentation frameworks such as Swagger
.
I always use the [Route]
attribute to define the endpoint path.
In your case, I would set it up as so:
[HttpGet, Route("usuario/{id}")]
[ProducesResponseType(StatusCodes.Status200OK, Type = typeof(Usuario))]
[ProducesResponseType(StatusCodes.Status404NotFound)]
public IActionResult GetUser(int id)
{
using (var db = new prueba2Context())
{
var usuario = await db.Usuario.Where(x => x.Id == id).FirstOrDefault();
if (usuario == null)
{
return NotFound();
}
return Ok(usuario);
}
}
Upvotes: 1
Reputation: 617
Is more common use "Route"
like that
`[Route("usuario")]
public ActionResult<Usuario> Get(int id)
{
using (var db = new prueba2Context())
{
var usuario = db.Usuario.Where(x => x.Id == id).FirstOrDefault();
if (usuario == null)
{
return NotFound();
}
return Ok(usuario);
}
}
`
Upvotes: 0