Creating an URL to a WebAPI ApiController inside an ASP.NET MVC View

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.

Advertisement

Tags: , ,

2 Responses to “Creating an URL to a WebAPI ApiController inside an ASP.NET MVC View”

  1. Matt Hancock Says:

    I had seen a few other complex solutions to this problem, but this is perfect and simple! Thanks for sharing.

  2. AHMED THARWAT Says:

    I’m new in MVC and need more details
    I can’t decide which Url.RouteUrl to change

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s


%d bloggers like this: