I'm setting up backend for my Windows Phone 8.1 App. I'm using ASP.net WebApi to create RESTful api for accessing data from DB, which is set up on Windows Azure.
This is how my routes looks:
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultNamedApi",
routeTemplate: "api/{controller}/{name}",
defaults: new { name = RouteParameter.Optional }
);
What i'm trying to achieve is accesing data using not an integer - I want to access data using a string. This is code from my WebApi controller:
private SmokopediaContext db = new SmokopediaContext();
// GET api/Images
public IQueryable<ImageModel> GetImageModels()
{
return db.ImageModels;
}
// GET api/Images/5
[ResponseType(typeof(ImageModel))]
public IHttpActionResult GetImageModel(int id)
{
ImageModel imagemodel = db.ImageModels.Find(id);
if (imagemodel == null)
{
return NotFound();
}
return Ok(imagemodel);
}
public IHttpActionResult GetImageModel(string name)
{
ImageModel imagemodel = db.ImageModels.Find(name);
if(imagemodel == null)
{
return NotFound();
}
return Ok(imagemodel);
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
db.Dispose();
}
base.Dispose(disposing);
}
private bool ImageModelExists(int id)
{
return db.ImageModels.Count(e => e.ID == id) > 0;
}
Most important code is an overload to GetImageModel with string parameter.
Server is returning error which says that parameter of url is incorrect:
<Error><Message>The request is invalid.</Message><MessageDetail>The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32' for method 'System.Web.Http.IHttpActionResult GetImageModel(Int32)' in 'Smokopedia.Controllers.DragonController'. An optional parameter must be a reference type, a nullable type, or be declared as an optional parameter.</MessageDetail></Error>
What should I correct in my route?
There is no difference in URI template terms between api/{controller}/{id} and api/{controller}/{name}; the arbitrary names you assign to the parameters can't be used in resolving the route.
Take a look at Overload web api action method based on parameter type for an example of how to "overload" routes based on parameter types.
Use Attribute Routing:
[Route("api/Images/{id:int}")]
public IHttpActionResult GetImageModel(int id){ do something}
[Route("api/Images/{id}")]
public IHttpActionResult GetImageModel(string id) {do something}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With