Я очень новичок как в угловых, так и в .net ядрах.Я пишу пример проекта. В этом проекте я вызываю метод из angular в .net core.Я получаю сообщение об ошибке:
Failed to load resource: the server responded with a status of 404 () api/AllItProjectsLists/index:1
У меня есть точки останова на угловой стороне метода getProjectDetails ().ничего не происходит, когда я нажимаю F11 в этой строке
return this._http.get(this.myAppUrl + 'api/AllItProjectsLists/Index').pipe(map(
Ниже приведен мой полный угловой код:
import { Injectable, Inject } from '@angular/core';
import { HttpClient, HttpInterceptor } from '@angular/common/http';
import { map } from 'rxjs/operators';
import { AllItProject } from '../../models/allitproject';
@Injectable({
providedIn: 'root'
})
export class ProjectDetailService {
myAppUrl = '';
constructor(private _http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
this.myAppUrl = baseUrl;
}
getProjectDetails() {
return this._http.get(this.myAppUrl + 'api/AllItProjectsLists/Index').pipe(map(
response => {
return response;
}));
}
В моем контроллере .net я определил AllItProjectsLists:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ProjectDetails.Models;
using ProjectDetails.Data;
using ProjectDetails.Interfaces;
namespace ProjectDetails.Controllers
[Route("api/[controller]")]
[ApiController]
public class AllItProjectsListsController : ControllerBase
{
private readonly KPIContext _context;
private readonly IProject objProject;
public AllItProjectsListsController(IProject _objProject)
{
objProject = _objProject;
}
[HttpGet]
[Route("api/AllItProjectsLists/Index")]
public IEnumerable<AllItProjectsList> Index()
{
return objProject.GetAllProjectDetails();
}
}
это то, что у меня есть в моем файле .net startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<KPIContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
services.AddCors();
}
Загрузка продолжается ... в моем веб-браузере
Ошибка из окна консоли:
<code>Failed to load resource: the server responded with a status of 404 ()
core.js:6014 ERROR HttpErrorResponseerror: "<!DOCTYPE html>↵<html lang="en">↵<head>↵<meta charset="utf-8">↵<title>Error</title>↵</head>↵<body>↵<pre>Cannot GET /api/AllItProjectsLists/Index
↵ ↵ ↵ "заголовки: HttpHeaderslazyInit: () => {…} аргументы: (...) вызывающая сторона: (...) длина: 0name:" "__proto__:ƒ () [[FunctionLocation]]: http.js: 120 [[Scopes]]: Scopes [4] lazyUpdate: nullnormalizedNames: Map (0) {} __ proto__: Objectmessage: «Ответ об ошибке Http для https://localhost:44313/api/AllItProjectsLists/Index: 404 OK» имя.Subscriber.js: 185
Я изменил код, как вы сказали мне, и я получаю код состояния 500 ошибка:
Failed to load resource: the server responded with a status of 500 ()
core.js:6014 ERROR HttpErrorResponseerror: "<!DOCTYPE html>
↵<html lang="en" xmlns="http://www"headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}message: "Http failure response for https://localhost:44313/api/AllItProjectsLists/Index: 500 OK"name: "HttpErrorResponse"ok: falsestatus: 500statusText: "OK"url: "https://localhost:44313/api/AllItProjectsLists/Index"__proto__: HttpResponseBase
defaultErrorLogger @ core.js:6014
handleError @ core.js:6066
next @ core.js:40557
schedulerFn @ core.js:35335
__tryOrUnsub @ Subscriber.js:185
Ниже мой измененный код:
Вот как я изменил свой код:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ProjectDetails.Models;
using ProjectDetails.Data;
using ProjectDetails.Interfaces;
namespace ProjectDetails.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AllItProjectsListsController : ControllerBase
{
private readonly KPIContext _context;
private readonly IProject objProject;
public AllItProjectsListsController(IProject _objProject)
{
objProject = _objProject;
}
[HttpGet("Index")]
public IEnumerable<AllItProjectsList> Index()
{
return objProject.GetAllProjectDetails();
}
}
Весь мой код запуска:
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SpaServices.AngularCli;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using ProjectDetails.Models;
using Microsoft.EntityFrameworkCore;
namespace ProjectDetails
{
public class Startup
{
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<KPIContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
// In production, the Angular files will be served from this directory
services.AddSpaStaticFiles(configuration =>
{
configuration.RootPath = "ClientApp/dist";
});
services.AddCors();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Error");
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseStaticFiles();
app.UseSpaStaticFiles();
app.UseCors(x => x.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller}/{action=Index}/{id?}");
});
app.UseSpa(spa =>
{
// To learn more about options for serving an Angular SPA from ASP.NET Core,
// see https://go.microsoft.com/fwlink/?linkid=864501
spa.Options.SourcePath = "ClientApp";
if (env.IsDevelopment())
{
spa.UseAngularCliServer(npmScript: "start");
}
});
}
}
}
Вся моя ошибка:
Failed to load resource: the server responded with a status of 500 ()
core.js:6014
RROR HttpErrorResponseerror: "<!DOCTYPE html>
↵<html lang="en" xmlns="http://www"headers: HttpHeaderslazyInit: () => {…}arguments: (...)caller: (...)length: 0name: ""__proto__: ƒ ()[[FunctionLocation]]: http.js:120[[Scopes]]: Scopes[4]lazyUpdate: nullnormalizedNames: Map(0)size: (...)__proto__: Mapclear: ƒ clear()constructor: ƒ Map()delete: ƒ delete()entries: ƒ entries()forEach: ƒ forEach()get: ƒ ()has: ƒ has()keys: ƒ keys()set: ƒ ()size: (...)values: ƒ values()Symbol(Symbol.iterator): ƒ entries()Symbol(Symbol.toStringTag): "Map"get size: ƒ size()__proto__: Object[[Entries]]: Array(0)length: 0__proto__: Objectappend: ƒ append(name, value)applyUpdate: applyUpdate(update) { /** @type {?} */ const key = update.name.toLowerCase(); switch (update.op) { case 'a': case 's': /** @type {?} */ let value = (/** @type {?} */ (update.value)); if (typeof value === 'string') { value = [value]; } if (value.length === 0) { return; } this.maybeSetNormalizedName(update.name, key); /** @type {?} */ const base = (update.op === 'a' ? this.headers.get(key) : undefined) || []; base.push(...value); this.headers.set(key, base); break; case 'd': /** @type {?} */ const toDelete = (/** @type {?} */ (update.value)); if (!toDelete) { this.headers.delete(key); this.normalizedNames.delete(key); } else { /** @type {?} */ let existing = this.headers.get(key); if (!existing) { return; } existing = existing.filter((/** * @param {?} value * @return {?} */ value => {…}clone: ƒ clone(update)constructor: class HttpHeaderscopyFrom: copyFrom(other) { other.init(); Array.from(other.headers.keys()).forEach((/** * @param {?} key * @return {?} */ key => {…}delete: ƒ delete(name, value)forEach: forEach(fn) { this.init(); Array.from(this.normalizedNames.keys()) .forEach((/** * @param {?} key * @return {?} */ key => {…}get: ƒ get(name)getAll: ƒ getAll(name)has: ƒ has(name)init: init() { if (!!this.lazyInit) { if (this.lazyInit instanceof HttpHeaders) { this.copyFrom(this.lazyInit); } else { this.lazyInit(); } this.lazyInit = null; if (!!this.lazyUpdate) { this.lazyUpdate.forEach((/** * @param {?} update * @return {?} */ update => {…}keys: ƒ keys()maybeSetNormalizedName: ƒ maybeSetNormalizedName(name, lcName)set: ƒ set(name, value)__proto__: Objectmessage: "Http failure response for https://localhost:44313/api/AllItProjectsLists/Index: 500 OK"name: "HttpErrorResponse"ok: falsestatus: 500statusText: "OK"url: "https://localhost:44313/api/AllItProjectsLists/Index"__proto__: HttpResponseBase
любая помощь будет высоко оценена.