c# - ASP.NET WebAPI 和 Angular POST

标签 c# asp.net angularjs asp.net-web-api

<分区>

我有一个 WebAPI Controller

public class MyController : ApiController
{
    [HttpPost]
    public SomeResult MyAction(string name, string message)
    {
        return SomeResult.???;
    }
}

我有一个 Angular Controller 调用这个方法

$http
    .post("/api/My/MyAction", { name: "bob", message: "hello" })
    .then(function(xhr) { ... }, function(xhr) { ... });

我得到了这个结果

Server Error in '/' Application.

The resource cannot be found.

我做错了什么?

附言这不是 URL...当我使用 HttpGet 并将参数附加到查询字符串时它起作用。

最佳答案

对于 post 请求的多个属性,您可以在 Controller 中使用 [FromBody] 并制作一个 ViewModel 类。示例:

[HttpPost]
        public HttpResponseMessage UpdateNumber([FromBody]UpdateNumberViewModel model)
        {
           //To do business
            return Request.CreateResponse(HttpStatusCode.OK);
        }

更新 View 模型:

public class UpdateViewModel
    {
        public int Id{ get; set; }
        public string Title{ get; set; }

    }

Angular :

var model = {                    
                    Id: 1,
                    Title: 'Vai filhão'
                }

    $http.post('/api/controller/updateNumber/',model).then(function () { alert("OK"); }, function () {alert("something wrong"); });

您可以在此处查看有关 web api 如何工作的更多详细信息:https://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

关于c# - ASP.NET WebAPI 和 Angular POST,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40547507/

相关文章:

c# - 在 TabControl 中对 TabPages 进行分组

C# WPF 设计器异常 : animation object cannot be used to animate property 'Foreground'

c# - 按下按钮后运行事件

c# - 如何在 asp.net mvc3 中进行搜索

c# - SynchronizationContext 和 TaskScheduler 之间的概念区别是什么

asp.net - 在长时间运行的操作完成之前保留ASP.NET页的最佳方法是什么?

c# - 这些在 ASP.NET 中叫什么 <% : %>?

javascript - stub `window.location.reload` 用于单元测试 - "Some of your tests did a full page reload!"

angularjs 日期过滤器忽略撇号

angularjs - 是否可以设置 ng-view 来替换 : true?