You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core EF GET请求报Connection Reset错误求助

问题描述
  • 我正在开发一款简易笔记应用,后端采用ASP.Net Core搭配Entity Framework实现,前端基于Angular框架开发。
  • 应用预期运行逻辑为:启动时自动加载已保存在MySQL数据库中的笔记列表。
  • 但当前应用发起GET请求时返回Connection Reset错误,错误截图如下:
    错误截图
  • 此前我曾遇到CORS问题,通过在连接字符串中添加http://解决该问题后,便出现本次连接重置错误,检索了全网相关资料均未找到可行解决方案。

相关代码

Angular端 note.service.ts 代码

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs';
import { Note } from '../note';

@Injectable({
  providedIn: 'root'
})
export class NoteService {

  private url: string = "http://localhost:44353/api/NotesLists";

  constructor(private http: HttpClient) { }

  getNotes(): Observable<Note[]> {
    return this.http.get<Note[]>(this.url);
  }
}

Angular端 home组件代码(订阅响应逻辑)

import { Component, OnInit } from '@angular/core';
import { NoteService } from '../services/note.service';
import { Note } from '../note';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.scss']
})
export class HomeComponent implements OnInit {

  public notes: Note[] = [];
  
  constructor(private noteService: NoteService) { }

  ngOnInit(): void {
    this.noteService.getNotes()
        .subscribe(data => this.notes = data);
  }

}

ASP.NET Core 端 [HttpGet] 接口代码

[HttpGet]
public IActionResult Get()
{
    try
    {
        var response = _datacontext.NotesList
                                    .Include(notesList => notesList.Note)
                                    .ToList();

        if (response.Count == 0)
        {
            return NotFound();
        }

        return Ok(response);
    }
    catch (Exception e)
    {

        return StatusCode(500, e.Message);
    }
}

DataContext 定义代码

using Microsoft.EntityFrameworkCore;
using noteAppAPI.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace noteAppAPI.Helpers
{
    public class DataContext : DbContext
    {
        public DataContext(DbContextOptions<DataContext> option) : base(option)
        {

        }

        public DbSet<NotesList> NotesList { get; set; }
        public DbSet<Note> Notes { get; set; }
        
    }
}

解决方案

连接重置的核心原因是 请求协议和后端监听协议不匹配:
你前端写的请求地址是http://localhost:44353,但443开头的端口是ASP.NET Core默认分配的HTTPS监听端口,该端口仅接受HTTPS请求,用HTTP协议发起请求会被服务端直接断开连接,请求根本不会进入接口逻辑。

按以下顺序排查修复:

  • 修正请求协议
    把note.service.ts里的请求地址改成https://localhost:44353/api/NotesLists,先直接发起HTTPS请求测试连通性。
  • 正确配置CORS策略
    你之前靠修改数据库连接字符串解决CORS完全是误操作,CORS是浏览器和后端接口之间的跨域安全策略,和数据库连接没有任何关联,乱改连接字符串只会引入额外问题。正确配置方式如下:
    在.NET 6+的Program.cs(或旧版本的Startup.cs)中添加CORS规则,放行Angular开发服务的默认端口4200:
// 注册服务阶段,放在builder.Build()之前
builder.Services.AddCors(options =>
{
    options.AddDefaultPolicy(policy =>
    {
        policy.WithOrigins("http://localhost:4200")
              .AllowAnyHeader()
              .AllowAnyMethod();
    });
});

// 中间件阶段,放在app.UseHttpsRedirection()之后、app.UseAuthorization()之前
app.UseCors();
  • 修复接口序列化潜在问题
    如果改完上述配置后接口返回500错误,优先检查两个点:
    • 实体循环引用:如果NotesList和Note类存在双向导航属性(比如NotesList包含Note集合,Note类又包含NotesList导航属性),序列化时会出现循环引用报错。可以给不需要序列化的导航属性加[JsonIgnore]特性,或者全局配置JSON序列化规则忽略循环引用:
      builder.Services.AddControllers()
          .AddJsonOptions(options =>
          {
              options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
          });
      
    • 数据库连通性:直接在Get()接口的ToList()行加断点调试,看EF查询MySQL时是否抛出连接、配置相关异常,确认数据库连接字符串配置正确、数据库服务可正常访问。

内容的提问来源于stack exchange,提问作者Jesus Castañeda

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.02 04:42:35