简体   繁体   English

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

[英]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. 我可以通过调用Web API Controller函数使$ http.get()正常工作,但是当我尝试执行post()时,它将给出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#: 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 在地址中,确保您输入完整的地址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. 我也建议邮递员测试您的api: 邮递员您可以安装它,也可以使用chrome扩展名。

One more thing, i recommend building your own json in angular like this: 还有一件事,我建议像这样按角度构建自己的json:

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 希望它有效: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 对于发送对象,我在请求中使用了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
      }
   }); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 http.post从angularJS到c#Web api的简单对象为null或所有属性为null - http.post Simple object from angularJS to c# Web api either null or all properties are null 当 angular http.post 具有正确的值时,为什么 obj 值在 asp web API2 控制器中为空 - Why the obj value is null in asp web API2 controller when the angular http.post has the correct value AngularJS $ http.post()将null发送到ASP.NET Web API控制器方法 - AngularJS $http.post() sends null to ASP.NET web API controller method 使用简单类型参数的AngularJS $ http.post到ASP.NET Web API控制器 - AngularJS $http.post to ASP.NET Web API controller with simple type argument C# MVC AngularJS: Controller 方法已调用,但未从 $http.post() 方法接收值 - C# MVC AngularJS: Controller Methods invoked, but not receiving values from the $http.post() method 如何在角度$ http.post中传递对象和值,并在ASP .NET Web API中获取它们 - How to pass object and a value in angular $http.post and get those in asp .net web api C# [HttpPost] 字符串值通过 angular http.post 变为 null - C# [HttpPost] string value through angular http.post becomes null http.post在Angular 5中不起作用 - http.post not working in Angular 5 Web API 2返回错误并使http.post捕获它 - Web API 2 return an error and make http.post catch it 在C#中将字典作为参数传递给Http.Post - Pass a dictionary as a parameter in Http.Post in C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM