Reputation: 1835
How can i implement the following routing scheme
http://localhost/vitualdir/prefix/{id}/methodname?{encoded json defenition of object}
using asp.net webapi 2 route attributes ? My suggestions are :
firstly: add [RoutePrefix("prefix")]
to controller
secondly : implement the following defenition:
[Route("~/{id}/methodname")]
[HttpGet]
public async Task<IHttpActionResult> methodname([FromUri] JsonObjectFromUri object, int id)
{
But that code is not working as i want. Could you help me with it ?
Upvotes: 0
Views: 2197
Reputation: 852
'~' in the Route specified on an Action, overrides the Route prefix.
Try removing it. It should work.
eg.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Routing;
namespace MvcApplication2.Controllers
{
public class TestClass
{
public string Name { get; set; }
public int Age { get; set; }
}
[RoutePrefix("prefix")]
public class ValuesController : ApiController
{
// GET api/values
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
// GET api/values/5
[Route("{id}/methodname")]
public string Get(int id, [FromUri] TestClass objectFromUri)
{
return "value";
}
// POST api/values
public void Post([FromBody]string value)
{
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
public void Delete(int id)
{
}
}
}
Now if you pass the Properties in the TestClass as url parameters, WebAPI will automatically bind them to the objectFromUri object.
http://localhost:39200/prefix/1/methodname?name=ram&age=10
Upvotes: 2