【问题标题】:Routing from an angular front end to an asp.net core 3.1 backend从角度前端路由到 asp.net core 3.1 后端
【发布时间】:2021-04-01 13:09:20
【问题描述】:

So here is my backend .csproj。我正在做一个前端水疗中心,以角度连接到我在内存数据库中的后端。 I can connect to my database from the URL of my back end application like in the image. 我也可以通过这个header 提出邮递员请求并获得postman sucessfull responses...到目前为止一切顺利。在我的前端有一个问题。我有我的前端角度service package with the url i use in postman。 @ 987654326@ 不知何故,当我在邮递员中执行获取请求时,我无法获得“旅行”列表。我几乎 80% 确定错误在后端,因为我可以在其他后端应用程序中获取请求。所以我要把我的后端代码放在这里。

我的程序.cs

public class Program
{
    public static void Main(string[] args)
    {
        var host = CreateHostBuilder(args).Build();

        using (var scope = host.Services.CreateScope())
        using (var context = scope.ServiceProvider.GetService<AppDbContext>())
        {
            context.Database.EnsureCreated();
        }

        host.Run();
    }

    public static IHostBuilder CreateHostBuilder(string[] args) =>
        Host.CreateDefaultBuilder(args)
            .ConfigureWebHostDefaults(webBuilder =>
            {
                webBuilder.UseStartup<Startup>();
            });
}

launchSettings.json

我的启动.cs

public class Startup
{
    public IConfiguration Configuration { get; }

    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMemoryCache();


        services.AddControllers().ConfigureApiBehaviorOptions(options =>
        {


        });

        services.AddDbContext<AppDbContext>(options =>
        {
            options.UseInMemoryDatabase(Configuration.GetConnectionString("memory"));
        });


        services.AddScoped<ITripRepository, TripRepository>();
        services.AddScoped<ITripService, TripService>();
        services.AddScoped<IUnitOfWork, UnitOfWork>();
        services.AddAutoMapper(typeof(Startup));


    }

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }


        app.UseRouting();

        app.UseAuthorization();

        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    }
}

}

我的控制器:

[HttpGet]
    [ProducesResponseType(typeof(List<TripDTO>), 200)]
    public async Task<IEnumerable<TripDTO>> GetAllAsync()
    {
        var trips = await _tripService.ListAsync();
        var dtos = _mapper.Map<IEnumerable<Trip>, IEnumerable<TripDTO>>(trips);

        return dtos;
    }

编辑: 我在尝试获取的列表中执行前端 console.log 时遇到的错误是 enter image description here

EDIT2:AppDbContext 后端

public class AppDbContext : DbContext
{
    public DbSet<Trip> Trips { get; set; }
   

    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        
        builder.Entity<Trip>().ToTable("Trips");
        builder.Entity<Trip>().HasKey(p => p.Id);
        builder.Entity<Trip>().Property(p => p.Id).IsRequired().ValueGeneratedOnAdd();
        builder.Entity<Trip>().Property(p => p.Key).IsRequired().HasMaxLength(10);
        builder.Entity<Trip>().Property(p => p.IsEmpty).IsRequired();
        builder.Entity<Trip>().Property(p => p.Orientation).IsRequired();
        builder.Entity<Trip>().Property(p => p.LineKey).IsRequired().HasMaxLength(10);
        builder.Entity<Trip>().Property(p => p.PathKey).IsRequired().HasMaxLength(10);
        builder.Entity<Trip>().Property(p => p.IsGenerated).IsRequired();
        builder.Entity<Trip>().Property(p => p.PassingTimes)
        .HasConversion(
        v => JsonConvert.SerializeObject(v),
         v => JsonConvert.DeserializeObject<List<PassingTime>>(v));

        builder.Entity<Trip>().HasData
        (
            new Trip { Id = 100,Key="Trip:344",IsEmpty=false,Orientation=false,LineKey="Line:444",PathKey="Path:344",IsGenerated=true }, // Id set manually due to in-memory provider
            new Trip { Id = 1200,Key="Trip:1344",IsEmpty=false,Orientation=false,LineKey="Line:2444",PathKey="Path:3424",IsGenerated=true }
        );

   
    }
}

}

编辑 3:

HTML 
    <!DOCTYPE html>
<html>

<body>
  <h4>List of Trips</h4>
  <div class="list row">
    <div class="col-md-6">
      <ul class="list-group">
        <li class="list-group-item" *ngFor="let trip of trips; let i = index" [class.active]="i == currentIndex" (click)="setActiveTrip(trip, i)">
          {{ trip.key }}
        </li>
      </ul>
    </div>
    <div *ngIf="!currentTrip">
      <br />
      <p>Please click on a trip to see the details...</p>
    </div>
    <div class="col-md-6">
      <div *ngIf="currentTrip">
        <h4>Selected Trip Details</h4>
        <div>
            <div>
              <label><strong>Key:</strong></label> {{ currentTrip.key }}
            </div>
            
        </div>
      </div>
    </div>
  </div>
</body>

</html>

组件.cs

    import { Component, OnInit } from '@angular/core';
import { TripService } from 'src/app/masterdataviagem/services/trip-service';

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

  trips: any;
  currentTrip: any = null;
  currentIndex = -1;
  key = '';
  tripsList:any;

  constructor(private tripService:TripService) { this.tripsList=this.tripService.getAll()}

  ngOnInit(): void {
    this.retrieveTrips();
   
   
  }

  retrieveTrips() {
   this.trips= this.tripService.getAll().subscribe(
    data => {
      this.trips = data;
      console.log(data);
    },
    error => {
      console.log(error);
    });
   console.log(this.trips);
  }

  refreshList() {
    this.retrieveTrips();
    this.currentTrip = null;
    this.currentIndex = -1;
  }

  setActiveTrip(trip: any, index: number) {
    this.currentTrip = trip;
    this.currentIndex = index;
  }


}

【问题讨论】:

  • “我几乎 80% 确定错误在后端,因为我可以在其他后端应用程序中获取请求。”这实际上是否意味着相反,后端实际上工作正常?无论哪种方式,当您只显示一半通信的代码时,几乎不可能对客户端/服务器通信进行故障排除。
  • 你没有提到你遇到了什么错误
  • 我已经编辑了我得到的错误。抱歉... Claies,在这个项目中,我在 node.js 和 express 中做了一个后端,我可以在 angular 和后端之间路由而没有任何问题。在这个项目中,我做了一个 asp.net 核心后端,我想它在路由方面几乎是一样的。如果我在邮递员中成功完成请求,当我尝试在角度服务中路由时,我不应该正确吗?我将在几分钟后使用我的后端代码的更多示例代码进行编辑
  • 好吧,在没有看到大部分前端代码的情况下,还不清楚发生了什么,但是屏幕截图中的错误cannot find a differ supporting object 暗示您希望从服务器接收一系列项目,但是而是接收单个对象。也许您没有反序列化 JSON?
  • 粘土在这种东西中不知何故是新的。我正在做一个大学项目,我现在正在处理这个问题。所以反序列化是将 Json 数据转换为 .NET 对象。但我在哪里做呢?我想在我的 AppDbContext 中这样做?如果有帮助,我也会打印我的 AppDbContext。我现在要编辑

标签: c# angular angular-routing asp.net-core-3.0


【解决方案1】:

也许您必须在后端启用 CORS(我的猜测是浏览器控制台末尾的“未知错误”,即您的 console.log(error))。

您可以尝试使用这个 chrome 扩展来测试:https://chrome.google.com/webstore/detail/allow-cors-access-control/lhobafahddgcelffkeicbaginigeejlf?hl=en

如果您的后端响应显示启用了扩展,那么您必须启用 CORS:

https://docs.microsoft.com/en-us/aspnet/core/security/cors?view=aspnetcore-3.1#ecors

【讨论】:

  • 这解决了我的问题。非常感谢你!!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-09
  • 2021-01-19
相关资源
最近更新 更多