获取带有实体框架的请求错误(连接重置)

发布于 2025-02-05 14:26:16 字数 2701 浏览 3 评论 0原文

因此,我将使用带有ASP.NET核心的实体框架为我的后端和AngularJS制作一个简单的笔记应用程序。

预期的行为是,当应用程序启动时,它应该加载已经保存在我的数据库(mysql)中的注释列表

是,当我的应用程序执行get请求时,它会将以下错误:

在此之前,我对CORS有一个问题,我通过将http://添加到我的连接字符串中,解决了我解决的问题,然后解决了这个问题。我一直在互联网上寻找,但我似乎找不到答案。

这是我的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);
  }
}

这是我的家庭组件(我在这里订阅以获取响应):

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

}

和我的[httpget]在.net core上的请求

    [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以获取更好的上下文(ha!)

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

So I'm making a simple notes app using Entity Framework with ASP.Net Core for my backend and AngularJS for frontend.

The expected behaviour is that when the app initiates, it should load a list of notes that are already saved in my database (MySQL)

Thing is, when my app does the Get request it rertuns the following error:
enter image description here

Before this I had a problem with CORS that I solved by adding http:// to my connection string and after solving that, I got this. I've been looking all over the internet but I don't seem to find an answer.

This is my 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);
  }
}

This is my home component (where I subscrirbe to get the response):

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

}

And my [HttpGet] request on .Net Core

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

And my DataContext for better context (Ha!)

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凤舞天涯 2025-02-12 14:26:17

感谢@markhomer在评论中的建议。解决方案是:

note.service.ts

private url:string =“ http:// localhost:44353/api/notesLists”;

私有URL:string =“ http:// localhost:44353/api/notesLists”;

这将使我必须在我的API中启用CORS,以便HTTPS请求可以使用。

要在startup.cs中启用cors 添加configureservices方法:

        services.AddCors(c =>
        {
            c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
        });
        services.AddDbContext<DataContext>(option => {
            option.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
        });

以及configure> configure在同一文件中的方法:

        app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());

Thanks to @MarkHomer for his suggestion in the comments. The solution to this was:

Change connection string on note.service.ts from

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

to

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

This would lead me to have to enable CORS in my API so the HTTPS request would work.

To enable CORS in Startup.cs add in ConfigureServices method:

        services.AddCors(c =>
        {
            c.AddPolicy("AllowOrigin", options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
        });
        services.AddDbContext<DataContext>(option => {
            option.UseMySql(connectionString, ServerVersion.AutoDetect(connectionString));
        });

And also in Configure method in the same file:

        app.UseCors(options => options.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文