Ashok Reddy
Ashok Reddy

Reputation: 9

how to use the get as method parameter in web api

for using the query string parameters in post man to obtain single data i want to use the get method as the parameter when i am trying this public HttpResponseMessage test(int id) it is showing error that

No HTTP resource was found that matches the request URI 'http://localhost:53720/api/test/1'.

No type was found that matches the controller named 'test'.

the code is:

   public class DefaultController: ApiController {
    public object Conn { get; private set;}

    [Route("api/test/id")]
    [HttpGet]
    public HttpResponseMessage test(int id) {
     DataSet ds = new DataSet();
     string conname = ConfigurationManager.ConnectionStrings["con"].ConnectionString;
     SqlConnection conn = new SqlConnection(conname);
     conn.Open();
     SqlCommand cmd = new SqlCommand("select *from Employees", conn);
     SqlDataAdapter sda = new SqlDataAdapter(cmd);
     sda.Fill(ds);
     return new HttpResponseMessage {
      Content = new StringContent(JsonConvert.SerializeObject(ds), Encoding.UTF8, "application/json")
     };
    }
   } 

Upvotes: 0

Views: 175

Answers (1)

curiousBoy
curiousBoy

Reputation: 6834

Your id is a variable parameter in your route and your route does not look correct. Try with {} around id. Like below.

[Route("api/test/{id}")] // <===== notice that id is in {}
[HttpGet]
public HttpResponseMessage test(int id)

You can also use Route Constraints if you want to restrict how the parameters in the route template are matched. General syntax is {parameter:constraint}

So in your case, it would be something like:

[Route("api/test/{id:int}")]

Look here for more details

Upvotes: 1

Related Questions