我想调用 post asp net core controller action。
这是我的代码: 消息 Controller
[Route("api/[controller]")]
public class MessageController : Controller
{
[HttpPost]
public IActionResult AddBlog(string email)
{
//test
return View();
}
}
我的表单:
<form [formGroup]="contactForm" (ngSubmit)="onSubmitModelBased()">
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="email" formControlName="email" placeholder="email">
</div>
<button type="submit" class="btn btn-block btn-primary">Wyślij</button>
</form>
和我的组件 ts
public onSubmitModelBased() {
alert("test");
let body = JSON.stringify({ email: 'test@test.pl' });
let headers = new Headers({ 'Content-Type': 'application/json' });
this.http
.post('/api/Message/AddBlog', body, { headers: headers })
.subscribe(data => {
alert('ok');
}, error => {
alert('not ok');
});
}
我;看到 alert("test") 和 http.post 操作返回 alert('ok')。 我也在 Controller Action 中做了一个断点,但它还没有被捕获。
最佳答案
您的路线应该是:
[Route("api/[controller]/[action]")]
public class MessageController : Controller
{
[HttpPost]
public IActionResult AddBlog([FromBody] AddBlogModel model)
{
//test
return View();
}
}
您现在设置它的方式意味着当 POST 请求到达/api/message 时会触发操作。添加 action 占位符会使其按照您的预期接受对/api/message/addblog 的 POST 请求。
编辑:至于您的其他问题,您正在发送一个 JSON 对象,但希望 MVC 能够解决它。您将需要制作一个模型类,例如:
public class AddBlogModel
{
public string Email { get; set; }
}
然后像上面那样改变你的 Controller Action 。这将告诉 MVC Core 模型应该基于请求主体创建,也就是您的 JSON。该模型包含一个包含电子邮件地址的属性。
关于asp.net-mvc - Angular2 http post 无法捕获 Controller 操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41952542/