gpt4 book ai didi

c# - Angular 6 HttpClient Post 未命中 DotNet Core 2.2 API Controller 中的 API Post 方法

转载 作者:行者123 更新时间:2023-12-01 21:58:05 25 4
gpt4 key购买 nike

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

大多数情况下,它是轻而易举的,但 Web API 却让我受不了。我在几分钟内就开始工作了,但我花了一个星期的时间尝试了所有可能的方法来让 Web Post 正常工作。

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

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

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

  3. 选择模板:ASP.NET core Web Application

  4. 在辅助屏幕上,将顶部的下拉菜单设置为 .NET Core 和 ASP.NET Core 2.2

  5. 选择红色盾牌“A” Angular 模板

  6. 让项目拉下依赖并重建。

除以下内容外,一切都是 Microsoft 开箱即用的演示应用程序:

  1. 将按钮添加到屏幕。

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

  3. 在controller的get方法中添加输入参数

  4. 在 Controller 中添加一个非常简单的post方法

我也在努力DotNet Core 2.0/Angular 4.x。使用@angular/http使用完全相同的结果。获取非常容易,但我已经尝试了所有配置以让帖子正常工作。我也会为其他版本发布这样的帖子。现在,我只是想尽我所能去工作,而不再使用 AngularJS 1.x。

import { Component, Inject } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';

@Component({
selector: 'app-fetch-data',
templateUrl: './fetch-data.component.html'
})
export class FetchDataComponent {
public Http: HttpClient;
public BaseURL: string;
public HttpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
public startDateIndex = 0;
public forecasts: WeatherForecast[] = [];
public forecast: WeatherForecast = {
dateFormatted: "3/27/2020",
temperatureC: 0,
temperatureF: 32,
summary: "Cold Post"
};

constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
this.Http = http;
this.BaseURL = baseUrl;

http.get<WeatherForecast[]>(baseUrl + 'api/SampleData/WeatherForecasts')
.subscribe(result => { this.forecasts = result; }, error => console.error(error));
}
public OnClick(pControl: string) {
//console.log("LogOn.OnClick * pControl=" + pControl);
switch (pControl) {
case "Prior":
this.startDateIndex -= 5;
this.Http.get<WeatherForecast[]>(this.BaseURL + 'api/SampleData/WeatherForecasts/', { params: new HttpParams().set('startDateIndex', this.startDateIndex.toString()) })
.subscribe(result => { this.forecasts = result; }, error => console.error(error));
break;
case "Next":
this.startDateIndex += 5;
this.Http.get<WeatherForecast[]>(this.BaseURL + 'api/SampleData/WeatherForecasts/', { params: new HttpParams().set('startDateIndex', this.startDateIndex.toString()) })
.subscribe(result => { this.forecasts = result; }, error => console.error(error));
break;
case "Post":
console.log("Post * this.forecast=" + JSON.stringify(this.forecast) + "this.HttpOptions=" + JSON.stringify(this.HttpOptions));
this.Http.post<WeatherForecast>(this.BaseURL + '/api/SampleData/PostWeatherForecast/', this.forecast, this.HttpOptions);
}
}
}

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 table-striped' *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 Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;

namespace NG_22.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 WeatherForecast PostWeatherForecast([FromBody] WeatherForecast weatherForecast)
{
var forecast = weatherForecast;
//return weatherForecast;
return new WeatherForecast()
{
DateFormatted = DateTime.Now.ToString("d"),
TemperatureC = 30,
Summary = Summaries[2]
};
}



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);
}
}
}
}
}

最佳答案

解决了!!!!!!

问题是没有任何订阅。如果没有人在听,它就不会打扰邮政。我添加了一个 .subscribe,它运行良好。

import { Component, Inject } from '@angular/core';
import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http';

@Component({
selector: 'app-fetch-data',
templateUrl: './fetch-data.component.html'
})
export class FetchDataComponent {
public Http: HttpClient;
public BaseURL: string;
public HttpOptions = {
headers: new HttpHeaders({
'Content-Type': 'application/json'
})
};
public startDateIndex = 0;
public forecasts: WeatherForecast[] = [];
public forecast: WeatherForecast = {
dateFormatted: "3/27/2020",
temperatureC: 0,
temperatureF: 32,
summary: "Cold Post"
};

constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
this.Http = http;
this.BaseURL = baseUrl;

http.get<WeatherForecast[]>(baseUrl + 'api/SampleData/WeatherForecasts')
.subscribe(result => { this.forecasts = result; }, error => console.error(error));
}
public OnClick(pControl: string) {
//console.log("LogOn.OnClick * pControl=" + pControl);
switch (pControl) {
case "Prior":
this.startDateIndex -= 5;
this.Http.get<WeatherForecast[]>(this.BaseURL + 'api/SampleData/WeatherForecasts/', { params: new HttpParams().set('startDateIndex', this.startDateIndex.toString()) })
.subscribe(result => { this.forecasts = result; }, error => console.error(error));
break;
case "Next":
this.startDateIndex += 5;
this.Http.get<WeatherForecast[]>(this.BaseURL + 'api/SampleData/WeatherForecasts/', { params: new HttpParams().set('startDateIndex', this.startDateIndex.toString()) })
.subscribe(result => { this.forecasts = result; }, error => console.error(error));
break;
case "Post":
console.log("Post * this.forecast=" + JSON.stringify(this.forecast) + "this.HttpOptions=" + JSON.stringify(this.HttpOptions));
this.Http.post<WeatherForecast>(this.BaseURL + '/api/SampleData/PostWeatherForecast/', this.forecast, this.HttpOptions)
.subscribe(result => { console.log("Posted" + JSON.stringify(result)); }, error => console.error(error));
}
}
}

interface WeatherForecast {
dateFormatted: string;
temperatureC: number;
temperatureF: number;
summary: string;
}

关于c# - Angular 6 HttpClient Post 未命中 DotNet Core 2.2 API Controller 中的 API Post 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55174352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com