我有一个 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