繁体   English   中英

Angular 4 Http Post 未命中 DotNet Core 2.0 API 控制器中的 API Post 方法

[英]Angular 4 Http Post not hitting API Post Method in DotNet Core 2.0 API Controller

我已经从 MVC/AngularJS 1.x 升级到 DotNet Core 2.0/Angular 4.x。 使用@angular/common/http

大多数情况下,它是轻而易举的,但 Web API 正在扼杀我。 我在几分钟内就可以开始工作,但我花了一周的时间在阳光下尝试一切以使 Web Post 正常工作。

我在这里所做的很容易复制。

进入 Visual Studio 17 并单击文件/新建项目

选择已安装/Visual C#/.NET Core

选择模板:ASP.NET core Web Application

在辅助屏幕上将顶部的下拉列表设置为 .NET Core 和 ASP.NET Core 2.0

选择红盾“A”角模板

让项目拉下依赖并重建。

一切都是微软提供的开箱即用演示应用程序,除了:

将按钮添加到屏幕上。

将代码添加到 .ts 以调用 API Controller

将输入参数添加到控制器中的 get 方法

给控制器添加一个非常简单的post方法

我也在尝试获得 DotNet Core 2.2/Angular 6.x。 使用@angular/httpclient 处理完全相同的结果。 获取非常简单,但我已经尝试了各种配置以使帖子正常工作。 我也会为其他版本发布这样的帖子。 现在,我只是想尽我所能,把 Angularjs 1.x 抛在脑后。

 import { Component, Inject } from '@angular/core'; import { Http, URLSearchParams, Headers } from '@angular/http'; @Component({ selector: 'fetchdata', templateUrl: './fetchdata.component.html' }) export class FetchDataComponent { public Http: Http; public BaseURL: string; public Headers: Headers; public startDateIndex = 0; public forecasts: WeatherForecast[] = []; public forecast: WeatherForecast = { dateFormatted: "3/27/2020", temperatureC: 0, temperatureF: 32, summary: "Cold Post" }; constructor(http: Http, @Inject('BASE_URL') baseUrl: string) { this.Http = http; this.BaseURL = baseUrl; this.Headers = new Headers(); this.Headers.append('Content-Type', 'application/json'); http.get(baseUrl + 'api/SampleData/WeatherForecasts').subscribe(result => { this.forecasts = result.json() as WeatherForecast[]; }, error => console.error(error)); } public OnClick(pControl: string) { //console.log("LogOn.OnClick * pControl=" + pControl); switch (pControl) { case "Prior": this.startDateIndex -= 5; var params = new URLSearchParams; params.set("startDateIndex", this.startDateIndex.toString()); this.Http.get(this.BaseURL + 'api/SampleData/WeatherForecasts/', { params: params }).subscribe(result => { this.forecasts = result.json() as WeatherForecast[]; }, error => console.error(error)); break; case "Next": this.startDateIndex += 5; var params = new URLSearchParams; params.set("startDateIndex", this.startDateIndex.toString()); this.Http.get(this.BaseURL + 'api/SampleData/WeatherForecasts/', { params: params }).subscribe(result => { this.forecasts = result.json() as WeatherForecast[]; }, error => console.error(error)); break; case "Post": console.log("Post * this.forecast=" + JSON.stringify(this.forecast)); var params = new URLSearchParams; params.set("weatherForecast", JSON.stringify(this.forecast)); this.Http.post(this.BaseURL + '/api/SampleData/PostWeatherForecast/', this.forecast, { headers: this.Headers }); } } } interface WeatherForecast { dateFormatted: string; temperatureC: number; temperatureF: number; summary: string; }
 <h1>Weather forecast</h1> <p>This component demonstrates fetching data from the server.</p> <p *ngIf="!forecasts"><em>Loading...</em></p> <table class='table' *ngIf="forecasts"> <thead> <tr> <th>Date</th> <th>Temp. (C)</th> <th>Temp. (F)</th> <th>Summary</th> </tr> </thead> <tbody> <tr *ngFor="let forecast of forecasts"> <td>{{ forecast.dateFormatted }}</td> <td>{{ forecast.temperatureC }}</td> <td>{{ forecast.temperatureF }}</td> <td>{{ forecast.summary }}</td> </tr> </tbody> </table> <button class='btn btn-default pull-left' (click)="OnClick('Prior')">Previous</button> <button class='btn btn-default pull-left' (click)="OnClick('Next')">Next</button> <button class='btn btn-default pull-right' (click)="OnClick('Post')">Post</button>

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

namespace NG_20.Controllers
{
    [Route("api/[controller]")]
    public class SampleDataController : Controller
    {
        private static string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        [HttpGet("[action]")]
        public IEnumerable<WeatherForecast> WeatherForecasts(int startDateIndex = 0)
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                DateFormatted = DateTime.Now.AddDays(index + startDateIndex).ToString("d"),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            });
        }

        [HttpPost("[action]")]
        public bool PostWeatherForecast([FromBody] WeatherForecast weatherForecast)
        {
            var forecast = weatherForecast;
            return true;
        }



        public class WeatherForecast
        {
            public string DateFormatted { get; set; }
            public int TemperatureC { get; set; }
            public string Summary { get; set; }

            public int TemperatureF
            {
                get
                {
                    return 32 + (int)(TemperatureC / 0.5556);
                }
            }
        }
    }
}

解决了! 它不会在没有订阅者的情况下进行 API 调用。

 import { Component, Inject } from '@angular/core'; import { Http, URLSearchParams, Headers } from '@angular/http'; @Component({ selector: 'fetchdata', templateUrl: './fetchdata.component.html' }) export class FetchDataComponent { public Http: Http; public BaseURL: string; public Headers: Headers; public startDateIndex = 0; public forecasts: WeatherForecast[] = []; public forecast: WeatherForecast = { dateFormatted: "3/27/2020", temperatureC: 0, temperatureF: 32, summary: "Cold Post" }; constructor(http: Http, @Inject('BASE_URL') baseUrl: string) { this.Http = http; this.BaseURL = baseUrl; this.Headers = new Headers(); this.Headers.append('Content-Type', 'application/json'); http.get(baseUrl + 'api/SampleData/WeatherForecasts').subscribe(result => { this.forecasts = result.json() as WeatherForecast[]; }, error => console.error(error)); } public OnClick(pControl: string) { //console.log("LogOn.OnClick * pControl=" + pControl); switch (pControl) { case "Prior": this.startDateIndex -= 5; var params = new URLSearchParams; params.set("startDateIndex", this.startDateIndex.toString()); this.Http.get(this.BaseURL + 'api/SampleData/WeatherForecasts/', { params: params }) .subscribe(result => { this.forecasts = result.json() as WeatherForecast[]; }, error => console.error(error)); break; case "Next": this.startDateIndex += 5; var params = new URLSearchParams; params.set("startDateIndex", this.startDateIndex.toString()); this.Http.get(this.BaseURL + 'api/SampleData/WeatherForecasts/', { params: params }) .subscribe(result => { this.forecasts = result.json() as WeatherForecast[]; }, error => console.error(error)); break; case "Post": console.log("Post * this.forecast=" + JSON.stringify(this.forecast)); this.Http.post(this.BaseURL + '/api/SampleData/PostWeatherForecast/', this.forecast, { headers: this.Headers }) .subscribe(result => { alert("Posted" + JSON.stringify(result.json())); }, error => console.error(error)); break; } } } interface WeatherForecast { dateFormatted: string; temperatureC: number; temperatureF: number; summary: string; }

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace NG_20.Controllers
{
    [Route("api/[controller]/[action]")]
    public class SampleDataController : Controller
    {
        private static string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        [HttpGet]
        public IEnumerable<WeatherForecast> WeatherForecasts(int startDateIndex = 0)
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                DateFormatted = DateTime.Now.AddDays(index + startDateIndex).ToString("d"),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            });
        }

        [HttpPost]
        public object PostWeatherForecast([FromBody] object weatherForecast)
        {
            var forecast = JObject.Parse(weatherForecast.ToString()).ToObject<WeatherForecast>();
            var x = forecast.DateFormatted;
            return weatherForecast;
        }



        public class WeatherForecast
        {
            public string DateFormatted { get; set; }
            public int TemperatureC { get; set; }
            public string Summary { get; set; }

            public int TemperatureF
            {
                get
                {
                    return 32 + (int)(TemperatureC / 0.5556);
                }
            }
        }
    }
}

改进的答案。 不需要接口和其他较小的改进和删除不必要的代码。

 import { Component, Inject } from '@angular/core'; import { Http, URLSearchParams, Headers } from '@angular/http'; @Component({ selector: 'fetchdata', templateUrl: './fetchdata.component.html' }) export class FetchDataComponent { public Http: Http; public BaseURL: string; public Headers: Headers; public startDateIndex = 0; public forecasts = []; public forecast = { dateFormatted: "3/27/2020", temperatureC: 0, temperatureF: 32, summary: "Cold Post" }; constructor(http: Http, @Inject('BASE_URL') baseUrl: string) { this.Http = http; this.BaseURL = baseUrl; this.Headers = new Headers(); this.Headers.append('Content-Type', 'application/json'); http.get(baseUrl + 'api/SampleData/WeatherForecasts') .subscribe(result => this.forecasts = result.json(), error => console.error(error)); } public OnClick(pControl: string) { //console.log("LogOn.OnClick * pControl=" + pControl); switch (pControl) { case "Prior": this.startDateIndex -= 5; var params = new URLSearchParams; params.set("startDateIndex", this.startDateIndex.toString()); this.Http.get(this.BaseURL + 'api/SampleData/WeatherForecasts/', { params: params }) .subscribe(result => this.forecasts = result.json(), error => console.error(error)); break; case "Next": this.startDateIndex += 5; var params = new URLSearchParams; params.set("startDateIndex", this.startDateIndex.toString()); this.Http.get(this.BaseURL + 'api/SampleData/WeatherForecasts/', { params: params }) .subscribe(result => this.forecasts = result.json(), error => console.error(error)); break; case "Post": console.log("Post * this.forecast=" + JSON.stringify(this.forecast)); this.Http.post(this.BaseURL + '/api/SampleData/Post/', this.forecast, { headers: this.Headers }) .subscribe(result => alert("Posted" + JSON.stringify(result.json())), error => console.error(error)); break; } } }

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;

namespace NG_20.Controllers
{
    [Route("api/[controller]/[action]")]
    public class SampleDataController : Controller
    {
        private static string[] Summaries = new[]
        {
            "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
        };

        [HttpGet]
        public IEnumerable<WeatherForecast> WeatherForecasts(int startDateIndex = 0)
        {
            var rng = new Random();
            return Enumerable.Range(1, 5).Select(index => new WeatherForecast
            {
                DateFormatted = DateTime.Now.AddDays(index + startDateIndex).ToString("d"),
                TemperatureC = rng.Next(-20, 55),
                Summary = Summaries[rng.Next(Summaries.Length)]
            });
        }

        [HttpPost]
        public object Post([FromBody] object weatherForecast)
        {
            var forecast = JObject.Parse(weatherForecast.ToString()).ToObject<WeatherForecast>();
            var x = forecast.DateFormatted;
            return weatherForecast;
        }



        public class WeatherForecast
        {
            public string DateFormatted { get; set; }
            public int TemperatureC { get; set; }
            public string Summary { get; set; }

            public int TemperatureF
            {
                get
                {
                    return 32 + (int)(TemperatureC / 0.5556);
                }
            }
        }
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM