I wonder what's the recommended way to handle data (ViewModels) in Web Api 2.. I have googled around quite much, and found some "recepies" but i wonder what's the most flexible and easy way of handling this..
This call returns error -->
GET http://localhost:63203/api/Gallery/GetPhotosForPage 404 (Not Found)
probably because of some signature error..,.
Here is the $http call (Angular) :
var currPage = $location.path() || "Unknown";
$http({
method: 'GET',
url: '/api/Gallery/GetPhotosForPage',
accept: 'application/json',
data: JSON.stringify(currPage) //currpage = ex. "/leftwing"
})
.success(function (result) {
console.log(result);
$scope.mystuff= result;
});
Here is the Controller GET method : /PriPhotosModel is the viewmodel...
[HttpGet]
public object GetPhotosForPage(string currPage)
{
PhotoServices photoService = new PhotoServices();
List<PriPhotosModel> priPhotos = photoService.GetPriPhotosForAllPhotographersOnPage(currPage);
return Request.CreateResponse(HttpStatusCode.OK, priPhotos);
}
Please note that WebApi works based on reflection this means that your curly braces {vars} must match the same name in your methods.
Therefore to match a sample URL like api/gallery/test
based on the default template "api/{controller}/{id}"
Your method needs to be declared like this:
[HttpGet]
public object GetPhotosForPage(string id){
return id;
}
Where the parameter string currPage
was replaced by string id
.
The reason why is because the default routing declares the parameter with name id
:
RouteTable.Routes.MapHttpRoute(name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = System.Web.Http.RouteParameter.Optional });
Web Api v1 defines resources globally in the global.asax on application_start event. Assuming you are using Visual Studio 2013 and based Microsoft default template your method may look like this:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
}
The WebApi routing configuration occurs in the WebApiConfig.Register
while the MVC configuration occurs in the RouteConfig.RegisterRoutes
Regarding WebApi v2 which introduced something called Route Attributes those can be used along with your Controller class and can facilitate the routing configuration.
For example:
public class BookController : ApiController{
//where author is a letter(a-Z) with a minimum of 5 character and 10 max.
[Route("sample/{id}/{newAuthor:alpha:length(5,10)}")]
public Book Get(int id, string newAuthor){
return new Book() { Title = "SQL Server 2012 id= " + id, Author = "Adrian & " + newAuthor };
}
[Route("otherUrl/{id}/{newAuthor:alpha:length(5,10)}/{title}")]
public Book Get(int id, string newAuthor, string title){
return new Book() { Title = "SQL Server 2012 id= " + id, Author = "Adrian & " + newAuthor };
}
...