【问题标题】:Angular2 Final release Http Post not working in MVCAngular2最终版本的Http Post在MVC中不起作用
【发布时间】:2017-07-09 10:25:26
【问题描述】:

我无法从 Angular 服务调用 MVC APIController。任何人都可以帮忙。谢谢。

我的Route.Config如下图。我允许所有路由。

public class RouteConfig
  {
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{*anything}",     //"{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

当我从应用程序调用帖子时,它不工作也不会引发任何错误。

forms.service.ts 文件中的代码

    createForm(post: myForm) {

    console.log('Actual object: ' + JSON.stringify(post));
    console.log(JSON.stringify(post));
    return this._http.post(this._posturl, JSON.stringify(post)).map(response => response.json());
    }

来自 API 控制器的代码

  public class MinPostController : ApiController
{
   public MinPostController()
    {

    }

    [System.Web.Http.HttpPost]
    public ActionResult CreateForm([FromBody] PostFormModel input)
    {
         //Check if the post is hitting.
         bool status = false; 
    }

}

当我使用 Fiddler 发布 Json 时,它工作正常,如下所示。请在下面找到图片。

【问题讨论】:

  • 按 F12 时“网络”标签会显示什么?
  • @CodeNotFound 我附上了网络标签的图片。当我点击帖子时,网络选项卡中没有任何新内容
  • 您确定在您的组件中调用了http.post 吗?换句话说,你用过subscribe吗?
  • onSubmit() { this._formsService.createForm(this.myform.value);当在我的 component.ts 中单击按钮时,将调用上述方法
  • 我没有使用任何订阅方法

标签: angular asp.net-mvc-4 angular-ui-router angular2-services


【解决方案1】:

你能在标题中添加Content-Type,看看有什么不同吗?

return this._http.post(this._posturl, JSON.stringify(post), this.getRequestOptions())
   .map(response => response.json())
   .catch(this.handleError);

private getRequestOptions() {
   return new RequestOptions({
      headers: new Headers({
         "Content-Type": "application/json"
      })
  });
}

private handleError(error: Response) {
   console.error(error);
}

【讨论】:

  • 我试过了....我还是没弄清楚是什么问题。 GET 在哪里工作没有任何问题
【解决方案2】:

这就是答案。我必须创建一个 observable 然后订阅它。

https://stackoverflow.com/a/34948742/6707243

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-05-31
    • 2017-01-24
    • 2017-01-28
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2018-01-12
    • 2015-02-02
    相关资源
    最近更新 更多