Angular $ http.post()到C#Web API控制器

时间:2017-02-20 18:19:28

标签: c# angularjs asp.net-web-api2

我可以通过调用我的Web API控制器函数来获得$ http.get()正常工作但是当我尝试做一个post()时它会给出404。

角:

// 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);
        }

2 个答案:

答案 0 :(得分:1)

在地址中请务必写下整个地址http://localhost:56493/api/Store/UpdateField

我也建议邮递员测试你的api:Postman 您可以安装它或使用chrome扩展。

还有一件事,我建议像这样建立你自己的角度json:

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

并称之为:

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

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

希望它有效:D

答案 1 :(得分:1)

我所做的并且始终为我工作的是:

    [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);
            })
        }
    }

为了发送对象,我在请求中使用了一个javascript对象

   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
      }
   });