我想调用 post asp net core controller action 。
这是我的代码:消息控制器
[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');
});
}
I;看到警报("测试")和 http.post 操作返回警报('确定')。我还在控制器操作中设置了一个断点,但尚未在那里捕获。
您的路由应该是:
[Route("api/[controller]/[action]")]
public class MessageController : Controller
{
[HttpPost]
public IActionResult AddBlog([FromBody] AddBlogModel model)
{
//test
return View();
}
}
您现在设置它的方式意味着当 POST 请求到达/api/message 时会命中该操作。添加操作占位符使其按预期接受对/api/message/addblog 的 POST 请求。
编辑:至于您的其他问题,您正在发送一个JSON对象,但希望MVC能够解决它。您将需要创建一个模型类,例如:
public class AddBlogModel
{
public string Email { get; set; }
}
并按上述方式更改控制器操作。这将告诉 MVC Core 应基于请求正文(即 JSON)创建模型。该模型包含一个将包含电子邮件地址的属性。