Mic*_*ura 1 c# endpoint single-page-application asp.net-core angular
[已解决] - 评论中的解决方案
[问题]
我是这个行业的新手,所以请原谅我提出一个新手问题,但我现在在 ASP.Net Core 6 上挣扎,我认为我错过了一些简单的东西,但我完全陷入困境......所以,我尝试使用 C# 和 Angular SPA 制作一个简单的应用程序来计算 BMI。我在 .Net Core 5 中做到了,它工作正常,但由于某种原因,当我逐字复制所有函数时,它不想调用 .Net Core 6 中的控制器方法。我开始搜索5 和 6 版本之间发生了哪些变化,我发现 Startup.cs 丢失了,相反,他们将其与 Program.cs 合并。这会是一个“问题”吗?您可以在下面找到我的 TS 组件代码和控制器代码。如果你能给出任何提示可能是什么问题以及为什么它适用于 5,但不适用于 6...
现在,我只想从 BmiController 调用 Get() 方法并接收 200 状态代码,仅此而已,但每次发送 http get 请求时,我都会收到 404 not found。
预先感谢您的帮助:)
程序.cs
using BMICalculatorCore.Core;
using BMICalculatorCore.Core.Interfaces;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddTransient<ICalculator, MetricCalculator>();
builder.Services.AddControllersWithViews();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (!app.Environment.IsDevelopment())
{
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseRouting();
app.MapControllerRoute(
name: "default",
pattern: "{controller}/{action=Index}/{id?}");
app.MapFallbackToFile("index.html"); ;
Run Code Online (Sandbox Code Playgroud)
bmicalculator.component.ts
import { HttpClient } from '@angular/common/http';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-bmicalculator',
templateUrl: './bmicalculator.component.html',
styleUrls: ['./bmicalculator.component.css']
})
export class BmicalculatorComponent implements OnInit {
public unit: string;
constructor(private http: HttpClient) {
this.unit = "Metric";
}
ngOnInit(): void {
}
sendRequest() {
this.http.get("https://localhost:44431/" + "bmictrl" + "/calculate").subscribe(result => {
}, error => console.error(error));
}
}
Run Code Online (Sandbox Code Playgroud)
BmiController.cs
using Microsoft.AspNetCore.Mvc;
namespace BMICalculatorCore.Controllers
{
[ApiController]
[Route("bmictrl")]
public class BmiController : ControllerBase
{
public BmiController()
{
}
[HttpGet]
[Route("calculate")]
public IActionResult Get()
{
return Ok();
}
}
Run Code Online (Sandbox Code Playgroud)
我解决了这个问题。看来,当 VS 创建项目时,它还为所有控制器(路径)创建了代理。当我创建新控制器时,缺少代理,这就是找不到端点的原因。我所做的是:
const { env } = require('process');
const target = env.ASPNETCORE_HTTPS_PORT ? `https://localhost:${env.ASPNETCORE_HTTPS_PORT}` :
env.ASPNETCORE_URLS ? env.ASPNETCORE_URLS.split(';')[0] : 'http://localhost:21346';
const PROXY_CONFIG = [
{
context: [
"/weather",
"/bmicalc", // this was added
"/helloworld", // this was added
"/bmicalculator" // this was added
],
target: target,
secure: false
}
]
module.exports = PROXY_CONFIG;
Run Code Online (Sandbox Code Playgroud)
添加代理允许应用程序到达端点。五分钟的工作,半天的搜索......
| 归档时间: |
|
| 查看次数: |
4122 次 |
| 最近记录: |