I am coding a C# web api 2 webservice and would like some help to get a single item from a request to a webservice.
Here is the web service controller class code:
[RoutePrefix("api")]
public class ItemsWebApiController : ApiController
Here is the web service function:
// GET: api/Getitem/1
[Route("Getitem")]
[System.Web.Http.HttpGet]
[ResponseType(typeof(Item))]
public async Task<IHttpActionResult> GetItem(int id)
{
Item item = await db.items.FindAsync(id);
if (item == null)
{
return NotFound();
}
return Ok(item);
}
Here is the uri to the IIS website:
Here is the uri that I am accessing:
http://localhost/thephase/api/Getitem/1
Here is the error that is being displayed in the browser:
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost/thephase/api/GetItem/1'.","MessageDetail":"No type was found that matches the controller named 'GetItem'."}
Here is the WebApiConfig code:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
}
The error states that the controller is named 'GetItem', and this is incorrect. Hence I am thinking that the problem is in the WebApiConfig route code.
If I remove the int id from the function, then the function is called correctly.
Here is the same function with no parameter:
// GET: api/Getitemnoparameter
[Route("Getitemnoparameter")]
[System.Web.Http.HttpGet]
[ResponseType(typeof(Item))]
public async Task<IHttpActionResult> GetItem()
{
Item item = await db.items.FindAsync(1);
if (item == null)
{
return NotFound();
}
return Ok(item);
}
The following uri accesses the function correctly:
http://localhost/thephase/api/Getitemnoparameter
So the problem has something to do with the int parameter.
Can someone please help me to get access the GetItem function with a parameter?
GetitemversusGetItem)?