简体   繁体   中英

Angular $http.post() to C# Web API Controller

I can get $http.get() working just fine with calling my Web API Controller function but when I try to do a post() it gives 404.

Angular:

// call API to update
$http.post("api/Store/UpdateField", $httpParamSerializer({ ID: rowEntity.ID, columnName: colDef.name, value: newValue}))
     .then(function (response) {

     },
     function (error, status) {
     });

C#:

[RoutePrefix("api/Store")]
public class StoreController : ApiController

    [Route("UpdateField")]
    [HttpPost]
    public async Task<bool> UpdateField(int ID, string columnName, string value)
    { // stuff here }
}


// routes
        public static void Register(HttpConfiguration config)
        {
            // Web API routes
            config.MapHttpAttributeRoutes();

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

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

            // Remove the XML formatter so json is returned instead
            config.Formatters.Remove(config.Formatters.XmlFormatter);
            config.Formatters.Add(config.Formatters.JsonFormatter);
        }

In the adress make sure you write the whole address http://localhost:56493/api/Store/UpdateField

Also I recommend postman for testing your api : Postman You can install it or either use the chrome extension.

One more thing, i recommend building your own json in angular like this:

var json = {
      "Id": $scope.id,
      "columnName": $scope.columnName,
      "value":$scope.value
    };

And call it like this:

$http.post("http://localhost:YOURPORT/api/Store/UpdateField", json)
     .then(function (response) {

     },
     function (error, status) {
     });

Hope it works :D

What i do and always work for me is:

    [HttpPost]
    [Route("MyRoute")]
    public HttpResponseMessage SaveEntity(MyModelOrCommand model)
    {
        try
        {
            object objReturned = bus.SendWithReturn(model);
            if (objReturned.GetType() == typeof(Validation))
            {
                return Request.CreateResponse(HttpStatusCode.BadRequest,                  ((Validation)objReturned).Messages);
            }
            return Request.CreateResponse(HttpStatusCode.OK, objReturned);
        }
        catch (Exception ex)
        {
            return Request.CreateResponse(HttpStatusCode.InternalServerError, ex);
        }
    }

   angular.module('MyModule').service('Module', ['envService', '$http', paService])
   function paService(envService, $http) {
   MyMethod: function (data, callback) {
            $http({
                method: 'POST',
                url: envService.read('apiUrl') + '/MyRoute',
                data: data,
            }).then(function (result) {
                callback(result);
            })
            .catch(function (result) {
                callback(result);
            })
        }
    }

And for send the object i use a javascript object in the request

   var obj = new Object();
   obj.MyProperty1 = $scope.data;
   obj.MyProperty2 = $scope.data2;
   myService.MyMethod(JSON.stringfy(obj),function(result){
      if(result.status == 200){
          //do stuff
      }
   }); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM