Niranjan Godbole Niranjan Godbole - 2 months ago 15
AngularJS Question

How to run WebApi?

Hi I am learning WebApi in VS2015. I have some experience in MVC4 so i know concepts of Routing in MVC$. I am following http://www.c-sharpcorner.com/uploadfile/65794e/web-api-with-angular-js/ website. I am trying to display some data from database as below.

public class TestController : ApiController
{
// GET: api/Test
public WebAPI db = new WebAPI();
public IEnumerable<LoginTbl> Get()
{
return db.LoginTbls.AsEnumerable();
}
}


WebApiConfig.cs as below.

config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{Test}/{id}",
defaults: new { id = RouteParameter.Optional }
);


Service.Js code.

app.service("APIService", function ($http) {
this.getSubs = function () {

return $http.Get("")
}
}
);


I am not sure what to pass in $http.Get("")
This is my index.cshtml

@{

}

<style>
table, tr, td, th {
border: 1px solid #ccc;
padding: 10px;
margin: 10px;
}
</style>
<h2>Welcome to Sibeesh Passion's Email List</h2>
<body data-ng-app="APIModule">
<div id="tblSubs" ng-controller="APIController">
<table>
<tr>
<th>UserName</th>
<th>Password</th>

</tr>
<tbody data-ng-repeat="sub in subscriber">
<tr>
<td>{{sub.UserName}}</td>
<td>{{sub.Password}}</td>

</tr>
</tbody>
</table>
</div>
</body>

<script src="~/Scripts/angular.js"></script>
<script src="~/Scripts/angular-route.js"></script>
<script src="~/Scripts/APIScripts/Module.js"></script>
<script src="~/Scripts/APIScripts/Service.js"></script>
<script src="~/Scripts/APIScripts/Controller.js"></script>


I am using AngularJs as clientscript. I am not sure how to run the above application as i can see two RouteConfig.cs and WebAPiconfig.cs. Someone tell me which file i should change in order to run the application? Thank you...

Answer

In the tutorial you're following, they don't actually say what they named the API controller, but it is called SubscriberController. The route matches up with api/ and then the word before the word Controller - so, api/Subscriber in the tutorial, and api/Test in your case.

In your angular routing configuration, your code would become $http.get("api/Test");

In order to return JSON from Web API, we'll need this line of code in your WebApiConfig.cs :

config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));

Comments