0

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 ?

1 Answer 1

2

'~' in the Route specified on an Action, overrides the Route prefix.

Try removing it. It should work.

Refer http://www.asp.net/web-api/overview/web-api-routing-and-actions/attribute-routing-in-web-api-2#prefixes

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

Sign up to request clarification or add additional context in comments.

1 Comment

I understand, thanks, but how can i take a json object from query string ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.