0

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.

enter image description here

granadaCoder
  • 26,328
  • 10
  • 113
  • 146
yavg
  • 2,761
  • 7
  • 45
  • 115
  • Are you using ASP.NET? or ASP.NET Core? – Andy Aug 22 '20 at 23:00
  • @Andy ASP.NET core – yavg Aug 22 '20 at 23:04
  • 1
    Gaaaaaa. That alters the response then. Note any nasties out there, I gave my answer before this was established. – granadaCoder Aug 22 '20 at 23:05
  • One, I have to delete my answer, because it it asp.net-core. 2. Please "tag" with asp.net core in the future any questions about asp.net-core (vs dot-net-framework). (3) I'm going to edit the tag here. (4) Technically, this is a repeat question : https://stackoverflow.com/questions/24843264/how-to-add-custom-methods-to-asp-net-webapi-controller – granadaCoder Aug 22 '20 at 23:08

2 Answers2

1

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);
    }
}
Andy
  • 12,859
  • 5
  • 41
  • 56
  • @yavg -- Please look in to `async` and `await` ... this is blocking code. You want to be as asynchronous as possible with your endpoints – Andy Aug 22 '20 at 23:10
  • If it is 'perfect' then "Mark As Answer" so this question does not come up under "not answered yet" SOF query-filters. – granadaCoder Aug 22 '20 at 23:11
  • @andy so yes, good piont. but .. you want to by async if the whole chain can be async-await'erized. see "turtle" talk : https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming#async-all-the-way – granadaCoder Aug 22 '20 at 23:13
  • https://i.imgur.com/UjIuerv.jpg (I am following your suggestion to return this async) but,I dont know how to solve that problem. I am using entity framework and from the database I built my models – yavg Aug 23 '20 at 00:20
  • @yavg -- try changing it to `FirstOrDefaultAsync()` – Andy Aug 23 '20 at 00:22
  • friend thank you very much, I hope not to bother you. but in terms of performance or advantages, I don't see how it improves using `async`. No more lines of code can be executed below while there is an `await` then one way or another it would be something` synchronous`. – yavg Aug 23 '20 at 01:00
  • @yavg -- you aren't bothering me in the least. But, I would google the pattern. It is a complicated subject. Just know you do not want your I/O bound calls to block. That will cause all kinds of problems for you down the road. – Andy Aug 23 '20 at 01:03
0

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);
        }
    }

`

Paulo
  • 577
  • 3
  • 8
  • 23