ASP.NET WebAPI和Angular的POST

4

我有一个WebAPI控制器。

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

我有一个Angular控制器调用这个方法。
$http
    .post("/api/My/MyAction", { name: "bob", message: "hello" })
    .then(function(xhr) { ... }, function(xhr) { ... });

我得到了以下结果

'/' 应用程序中的服务器错误。

找不到该资源。

我做错了什么?

附言:这不是URL的问题...当我使用 HttpGet 并将参数添加到查询字符串时,它可以工作。


请发布您的路由配置调用。 - toadflakz
请查看此问题的答案:http://stackoverflow.com/questions/40082163/webapi-httppost-endpoint-not-being-hit/40082757#40082757 - Marcus Höglund
这可能只是一个打字错误,但在您的示例中,操作名称是“MyAction”,但您在Angular中使用的URL是“MyAccount”。 此外,正如第一位评论者所说,查看路由配置将非常有用。 - ADyson
将“/api/MyController/MyAccount”更改为“/api/My/MyAccount”。 - Daniel
1
将这些参数用于POST请求的uri中,或封装在类中并标记为[FromBody]。 - Alex Lebedev
显示剩余3条评论
2个回答

2

我也遇到过这个问题,如果你在谷歌上搜索,会有不同的解决方法。其中最简单的方法是在WebApi控制器中只使用一个输入对象,所以在你的情况下只需创建一个类即可。

public class InputData {
    public string name { get; set; }
    public string message { get; set; }
}

然后将输入更改为具有[FromBody]前缀的新创建对象(可能不是强制性的,参见@ADyson评论)

public SomeResult MyAction([FromBody]InputData inputData)

对于这样的复杂类型,[FromBody] 不是必需的。只有在尝试将简单类型(例如字符串)传递到正文中时才需要它。请参阅 https://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api。 - ADyson
@ADyson感谢您的建议,从您提供的链接来看,似乎并不是必须的。 - Naigel

2

如果对于 post 请求有多个属性,您可以在控制器中使用 [FromBody] 并创建 ViewModel 类。示例如下:

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

UpdateViewModel:

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

1
与此处的另一个答案类似,对于这样的复杂类型,[FromBody]是不必要的。只有在尝试在正文中传递简单类型(例如字符串)时才需要它。请参阅https://www.asp.net/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api。 - ADyson
没错,我会编辑我的回答... - Kleyton Santos

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接