【问题标题】:Angular2 http post couln't catch controller actionAngular2 http post 无法捕捉控制器动作
【发布时间】:2017-01-31 16:44:30
【问题描述】:

我想调用 post asp net core 控制器动作。

这是我的代码: 消息控制器

[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')。 我还在控制器操作中设置了一个断点,但它还没有被捕获。

【问题讨论】:

  • 你能把你的Startup.cs文件的内容包括进来吗?
  • @Danoram 你想要startup.cs的哪一部分?

标签: asp.net-mvc http angular asp.net-core


【解决方案1】:

你的路由应该是:

[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)创建。该模型包含一个包含电子邮件地址的属性。

【讨论】:

  • 现在我收到 POST localhost:57572/api/Message/AddBlog 500(内部服务器错误)
  • 看我的编辑,至少你必须为数据定义一个视图模型。如果不是,那么您必须检查日志。
  • 我怎样才能把一些有角度的日志?现在我有 alert('not ok');
  • 使用浏览器 F12 工具查看服务器返回的内容。
  • 问题出在我的服务没有配置好。感谢您的帮助!
猜你喜欢
  • 2021-07-10
  • 2016-06-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-14
  • 1970-01-01
  • 2016-06-08
  • 1970-01-01
相关资源
最近更新 更多