首页 > 解决方案 > 从角度调用.net核心方法给出错误:加载资源失败:服务器响应状态为404()

问题描述

我对 Angular 和 .net 核心都很陌生。我正在编写一个示例项目,在这个项目中,我正在调用一个从 angular 到 .net 核心的方法。我不断收到错误消息:

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

我一直在加载...在我的网络浏览器上

来自控制台窗口的错误:

Failed to load resource: the server responded with a status of 404 ()
core.js:6014 ERROR HttpErrorResponseerror: "<!DOCTYPE html>↵&lt;html lang="en">↵&lt;head>↵&lt;meta charset="utf-8">↵&lt;title>Error</title>↵&lt;/head>↵&lt;body>↵&lt;pre>Cannot GET /api/AllItProjectsLists/Index</pre>↵&lt;/body>↵&lt;/html>↵"headers: HttpHeaderslazyInit: () => {…}arguments: (...)caller: (...)length: 0name: ""__proto__: ƒ ()[[FunctionLocation]]: http.js:120[[Scopes]]: Scopes[4]lazyUpdate: nullnormalizedNames: Map(0) {}__proto__: Objectmessage: "Http failure response for https://localhost:44313/api/AllItProjectsLists/Index: 404 OK"name: "HttpErrorResponse"ok: falsestatus: 404statusText: "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

我按照您告诉我的方式更改了代码,并且收到状态代码 500 错误:

Failed to load resource: the server responded with a status of 500 ()
core.js:6014 ERROR HttpErrorResponseerror: "<!DOCTYPE html>
↵&lt;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>
↵&lt;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

任何帮助将不胜感激。

标签: javascriptc#angulartypescriptasp.net-core

解决方案


你应该像这样改变你的代码

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

或者

[Route("api/[controller]/[action]")]
[ApiController]
public class AllItProjectsListsController : ControllerBase
{
    private readonly KPIContext _context;
    private readonly IProject objProject;

    public AllItProjectsListsController(IProject _objProject)
    {
        objProject = _objProject;

    }

    [HttpGet]
    public IEnumerable<AllItProjectsList> Index()
    {
        return objProject.GetAllProjectDetails();
    }
}

推荐阅读