Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Web API from MVC Application when both in same Solution

So I am totally new to the Web API and I thought to myself I would start a test project to learn it and AngularJS and how they can work together nicely ... etc.

I have created a multi-tier architecture within my solution, and inside my TPlan.API project, I have the following route configured in the Global.asax

GlobalConfiguration.Configuration.Routes.Add("default",
            new HttpRoute("api/{controller}"));

enter image description here

TPlan.WEB is my MVC application, and it is set up as "Start Up Project". When I run it, I want to be able to go to:

mysite:port/api/test

And get the value from the API from my test controller in there.

However it is not working for me, I get the following:

No HTTP resource was found that matches the request URI 'mysite:port/api/test'.

like image 591
J86 Avatar asked Jan 25 '14 21:01

J86


People also ask

How do Web API and MVC work together in the same project?

In order to add a Web API Controller you will need to Right Click the Controllers folder in the Solution Explorer and click on Add and then Controller. Now from the Add Scaffold window, choose the Web API 2 Controller – Empty option as shown below. Then give it a suitable name and click OK.


1 Answers

Er, in visual studio, right click on the solution and go to properties. Go to startup and select the "multiple projects" option and tick the website and the webservice to both start up.

That will start both of them. But as has been pointed out, they're running on separate ports, they're completely separate applications... I don't think you can register a route that belongs outside of the website.

We work like this

View => POST / GET => MVC Controller => HTTP Request => API Controller

So our mvc views post or get to our mvc controllers, and then we fire off a separate http request to the web api. this is a server to server call, its like calling any external web service. we wait for the response from the api and then return whatever is required to the view...

like image 92
spaceman Avatar answered Oct 13 '22 10:10

spaceman