Reputation: 37
i have angular.js code like this :
(function (appAN) {
'use strict';
appAN.controller('InfoController', function ($scope, $http) {
$scope.model = {
firstname: "john",
lastname: "doe",
company: 'IBM',
}
$scope.addbtn = function () {
var info = {
firstname: $scope.model.firstname,
lastname: $scope.model.lastname,
company: $scope.model.company
}
var url = "Info/AddInfo";
var data = JSON.stringify(info);
$http.post(url, data).success(function (data) {
alert(success);
});
}
});
}(angular.module('testd',[])));
and in c# code like this :
namespace testdemo.Controllers
{
public class InfoController : ApiController
{
[HttpPost]
public IHttpActionResult AddInfo([FromBody]InfoClass info)
{
object o = new object();
return Json(o);
}
}
public class InfoClass
{
public string firstname { get; set; }
public string lastname { get; set; }
public string company { get; set; }
}
}
now problem is : i am not able to get values in my c# method, breaking point is not hitting also at 'AddInfo' method.
Failed to load resource: the server responded with a status of 404 (Not Found) http://localhost:63498/Info/AddInfo
i am able to see the values untill : var data = JSON.stringify(info);
what is wrong with my code ?
my routing is like this :
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
}
}
Upvotes: 0
Views: 986
Reputation: 102
Make sure you have the following snippet in the webapiconfig.cs to call webapi.
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
Mention api url as follows in the "api/Info/AddInfo"
Upvotes: 0
Reputation: 5122
You should register your routes for ApiControllers in App_Start/WebApiConfig.cs. Something like this:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
And then use url like this:
var url = "/api/Info/AddInfo";
Upvotes: 1
Reputation: 4713
remove JSON.stringify from your code and directly pass info object in your $http.post. Angular will stringify it for you :)
You need to annotate your post handler for a rest end.
Add you post URL in RouteConfig
Upvotes: 0