I am using the .Net MVC4 Web API to (hopefully) implement a RESTful api. I need to pass in a few parameters to the system and have it perform some action, then return a lis
I just had to implement a RESTfull api where I need to pass parameters. I did this by passing the parameters in the query string in the same style as described by Mark's first example "api/controller?start=date1&end=date2"
In the controller I used a tip from URL split in C#?
// uri: /api/courses
public IEnumerable<Course> Get()
{
NameValueCollection nvc = HttpUtility.ParseQueryString(Request.RequestUri.Query);
var system = nvc["System"];
// BL comes here
return _courses;
}
In my case I was calling the WebApi via Ajax looking like:
$.ajax({
url: '/api/DbMetaData',
type: 'GET',
data: { system : 'My System',
searchString: '123' },
dataType: 'json',
success: function (data) {
$.each(data, function (index, v) {
alert(index + ': ' + v.name);
});
},
statusCode: {
404: function () {
alert('Failed');
}
}
});
I hope this helps...
I found exellent solution on http://habrahabr.ru/post/164945/
public class ResourceQuery
{
public string Param1 { get; set; }
public int OptionalParam2 { get; set; }
}
public class SampleResourceController : ApiController
{
public SampleResourceModel Get([FromUri] ResourceQuery query)
{
// action
}
}
Use Parameter Binding as describe completely here : http://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api
public HttpResponseMessage Get(int id,string numb)
{
//this will differ according to your entity name
using (MarketEntities entities = new MarketEntities())
{
var ent= entities.Api_For_Test.FirstOrDefault(e => e.ID == id && e.IDNO.ToString()== numb);
if (ent != null)
{
return Request.CreateResponse(HttpStatusCode.OK, ent);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Applicant with ID " + id.ToString() + " not found in the system");
}
}
}
Just add a new route to the WebApiConfig
entries.
For instance, to call:
public IEnumerable<SampleObject> Get(int pageNumber, int pageSize) { ..
add:
config.Routes.MapHttpRoute(
name: "GetPagedData",
routeTemplate: "api/{controller}/{pageNumber}/{pageSize}"
);
Then add the parameters to the HTTP call:
GET //<service address>/Api/Data/2/10
What does this record marking mean? If this is used only for logging purposes, I would use GET and disable all caching, since you want to log every query for this resources. If record marking has another purpose, POST is the way to go. User should know, that his actions effect the system and POST method is a warning.