我的应用程序出现错误,我似乎无法识别问题

问题描述 投票:0回答:1

Screenshot of Error 每当我想访问我的前端并且我不知道该怎么办时,我都会收到此错误

作者控制器 cs

// Controllers/AuthorController.cs
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Pencraft.Controllers
{
    [Route("api/[controller]")]
    [ApiController]
    public class AuthorController : ControllerBase
    {
        private readonly AppDbContext _context;

        public AuthorController(AppDbContext context)
        {
            _context = context;
        }

        [HttpGet]
        public async Task<ActionResult<IEnumerable<Author>>> GetAuthors()
        {
            var authors = await _context.Authors.ToListAsync();
            return Ok(authors);
        }

        [HttpGet("{id}")]
        public async Task<ActionResult<Author>> GetAuthor(int id)
        {
            Author? author = await _context.Authors.FindAsync(id);

            if (author == null)
            {
                // Return NotFound result if author is null
                return NotFound();
            }

            // Return the author value
            return Ok(author);
        }

        // Other actions for creating, updating, and deleting authors

        // Additional action method examples
        [HttpPost]
        public ActionResult<Author> CreateAuthor(Author newAuthor)
        {
            // Your logic to create a new author
            // ...

            // Return the newly created author
            return Ok(newAuthor);
        }

        [HttpPut("{id}")]
        public IActionResult UpdateAuthor(int id, Author updatedAuthor)
        {
            // Your logic to update the author with the specified id
            // ...

            // Return NoContent if successful
            return NoContent();
        }

        [HttpDelete("{id}")]
        public IActionResult DeleteAuthor(int id)
        {
            // Your logic to delete the author with the specified id
            // ...

            // Return NoContent if successful
            return NoContent();
        }
    }
}

启动.cs

using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Pencraft_app.pencraft_backend
{
    public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }

        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<AppDbContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"), b => b.MigrationsAssembly("Pencraft_app.pencraft_backend")));

            // Other services can be added here...

            services.AddCors(options =>
            {
                options.AddPolicy("AllowOrigin", builder =>
                {
                    builder.AllowAnyOrigin()
                           .AllowAnyHeader()
                           .AllowCredentials()
                           .AllowAnyMethod();
                });
            });

            services.AddControllers();
        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                // Production configuration goes here
            }

            app.UseRouting();
            app.UseDefaultFiles();
            app.UseStaticFiles();
            app.UseCors("AllowOrigin");  // Make sure this is before UseRouting()

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

                // Conventional routing for API controllers
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "api/{controller}/{action=Index}/{id?}");

                // If you still want a specific route for "AuthorApi," you can add it separately
                endpoints.MapControllerRoute(
                    name: "AuthorApi",
                    pattern: "api/author",
                    defaults: new { controller = "Author", action = "Index" });
            });

            
        }
    }

    public class AppDbContext : DbContext
    {
        public DbSet<YourEntity> YourEntities { get; set; }

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

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            // Configure your entities and relationships here

            // Example configuration for YourEntity
            modelBuilder.Entity<YourEntity>(entity =>
            {
                entity.HasKey(e => e.Id);
                entity.Property(e => e.Name).IsRequired();
                // Add other property configurations as needed
            });
        }
    }

    public class YourEntity
    {
        public int Id { get; set; }

        [Required]
        public string Name { get; set; }  = string.Empty;

        // Add other properties as needed
    }
}

我尝试了这个,尽管我在网上找到了所有建议,但我似乎无法解决这个问题。我不知道我做错了什么,因为 localhost/api/authors 也不存在,尽管我为它创建了一个端点

c# asp.net web localhost backend
1个回答
0
投票

您可能在自己的代码中找到答案!

在你的startup.cs中你有

app.UseRouting();
app.UseDefaultFiles();
app.UseStaticFiles();
app.UseCors("AllowOrigin");  // Make sure this is before UseRouting()

这表明您需要在 useRouting() 之前拥有 app.UseCors("AllowOrigin")。 因此将该部分更改为:

app.UseCors("AllowOrigin");  // Make sure this is before UseRouting()
app.UseRouting();
app.UseDefaultFiles();
app.UseStaticFiles();
       
© www.soinside.com 2019 - 2024. All rights reserved.