1
votes

I am using asp.net core 2 web API, I had created three methods first and third works fine but when I hit the second method it routed me to the first method did I write correct route or something is wrong with routes?

[Route("api/[controller]")]
public class HospitalController : Controller
{  
    [HttpGet]
    public IActionResult Get()
    {
        return new ObjectResult("");
    }

    [HttpGet("searchstring:aplha")]
    public IActionResult Get(string searchstring)
    {
       return new ObjectResult(searchstring);
    }


    [HttpGet("{Id:int}")]
    public IActionResult Get(int Id)
    {
        return new ObjectResult(Id);
    }
}
1

1 Answers

1
votes

Below is your corrected code:

[Route("api/[controller]")]
public class HospitalController : Controller
{

    [HttpGet]
    public IActionResult Get()
    {
        return new ObjectResult("");
    }

    [HttpGet("{searchstring}")]
    public IActionResult Get(string searchstring)
    {
        return new ObjectResult(searchstring);
    }


    [HttpGet("{Id:int}")]
    public IActionResult Get(int Id)
    {
        return new ObjectResult(Id);
    }
}

It will work properly for all the three methods, if you call URL like "/api/Hospital/1" for int values, "/api/Hospital/abc" for string values.