0

I am trying to figure out how to change the way my REST API is accessed. It's MVC architecture and currently one of my controllers looks like:

 [JsonpFilter]
 public class ItemController : Controller
 {
     public JsonResult GetItem(string id)
     {
         Item x = new Item(id);
         return Json(x, JsonRequestBehavior.AllowGet);
     }
 }

The reason you see the Jsonp filter is because I am accessing this API from a different domain through ajax and ajax doesn't support cross domain json requests.

So, right now you would access an Item like so because of the default routing:

api/Item/GetItem/4

However, I want to be able to do the following:

api/Item/4

and in the future be able to do something like

api/Item/4/Name

to get back just the name of the item with id 4.

How would I go about doing this? Thanks.

1 Answer 1

1

I'd really recommend Attribute Routing for MVC and Web API for specifying route information - http://attributerouting.net/

It is also built into the new version of MVC & Web API.

Its pretty simple to setup. You can just decorate your controller methods with an attribute like below in your case

[JsonpFilter]
[GET("api/Item/{id}")]
public JsonResult GetItem(string id)
{
  Item x = new Item(id);
  return Json(x, JsonRequestBehavior.AllowGet);
}
Sign up to request clarification or add additional context in comments.

Comments

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.