Introduction
Today I was trying to add some dynamic content to my new IT consulting website. My website is based on ASP.NET MVC, but I needed to load some dynamic content in one part of the page and I thought I would try out the new ASP.NET WebAPI framework for this.
Problem
Creating the ApiController was easy, but when I wanted to use the controller in my ASP.NET MVC view, I wasn’t sure how to include the Url of the controller. Hardcoding the address didn’t feel right, especially because for the MVC controllers you have the really useful Url.Action
method, which takes the name of an action and a controller and generates an URL to call this action. Unfortunately there wasn’t any built in method to call an ApiController. My first attempt was to use the following call instead, specifying the name of the route I want to use directly:
Url.RouteUrl("DefaultApi", new{controller="[CONTROLLERNAME]"})
Unfortunately, this didn’t work as expected — the function didn’t produce any Url.
After some googling I came across this stackoverflow post, with the missing piece of the puzzle:
Solution
Basically all you have to do is to add an empty httproute
parameter to the Url.RouteUrl
call. This apparently helps the system differentiate between normal routes and WebApi routes. So the final call looks like this:
Url.RouteUrl("DefaultApi", new{httproute = "", controller="[CONTROLLERNAME]"})
Keep in mind that the first parameter to RouteUrl
refers to the name of the route you used in the RegisterRoutes
function, which is “DefaultApi” by default.
Tags: ASP.NET MVC, Routing, WebAPI
February 25, 2013 at 5:03 pm |
I had seen a few other complex solutions to this problem, but this is perfect and simple! Thanks for sharing.
May 24, 2015 at 6:19 pm |
I’m new in MVC and need more details
I can’t decide which Url.RouteUrl to change