首页 > 解决方案 > 我可以在单个 asp net core 5 项目中结合 react 和 webapi 吗?

问题描述

我做了一个 webapi 项目。现在我正在尝试让项目对另一个任务做出反应。为了测试,我想将项目分成两部分 ui 和 api 服务。我开始从 webapi 项目添加代码以响应项目(通过重命名类、接口、字段等进行更改)。但 api 控制器不工作,招摇失败。

using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.HttpsPolicy;
using Microsoft.AspNetCore.SpaServices.ReactDevelopmentServer;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.OpenApi.Models;
using Microsoft.EntityFrameworkCore;

namespace TaskList
{
    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)
        {
            string connection = Configuration.GetConnectionString("DefaultConnection");

            services.AddDbContext<ITaskRepository,TaskContext>(options => options.UseSqlite(connection));

            services.AddControllers();

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "TaskList", Version = "v1" });
            });

            services.AddControllersWithViews();

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "TaskList v1"));
            }
            else
            {
                app.UseExceptionHandler("/Error");
                // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
                app.UseHsts();
            }

            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseSpaStaticFiles();

            app.UseRouting();

            app.UseAuthentication();
            
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                
                endpoints.MapControllerRoute(
                    name: "default",
                    pattern: "{controller}/{action=Index}/{id?}");
            });

            app.UseSpa(spa =>
            {
                spa.Options.SourcePath = "ClientApp";

                if (env.IsDevelopment())
                {
                    spa.UseReactDevelopmentServer(npmScript: "start");
                }
            });
        }
    }
}

using System;

using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;


[ApiController]
[Route("[controller]")]
class TaskController : ControllerBase
{
    private readonly ITaskRepository _repository;

    public TaskController(ITaskRepository r)
    {
        _repository = r;
    }

    [Route("GetAll")]
    [HttpGet]
    public async Task<IEnumerable<SheduledTask>> GetAll()
    {
        return await _repository.GetAll();
    }

    [Route("GetUnfineshedTasksEndingBefore")]
    [HttpGet]
    public async Task<IEnumerable<SheduledTask>> GetUnfineshedTasksEndingBefore(DateTime t)
    {
        return await _repository.GetUnfineshedTasksEndingBefore(t);
    }

    public class CreateParams
    {
        public string Name {get; set;}
        public DateTime Begin {get; set;}
        public DateTime End {get; set;}
    }

    [Route("Create")]
    [HttpPost]
    public async  Task<SheduledTask> Create(CreateParams p)
    {
        return await _repository.Create(p.Name, p.Begin, p.End);
    }

    [Route("SetFinished")]
    [HttpPost]
    public async Task<SheduledTask> SetFinished(string id)
    {
        return await _repository.SetFinished(id);
    }
}
    

大摇大摆的输出

API 请求结果

github中的所有代码:https ://github.com/al-al-se/TaskList

标签: c#asp.net-core

解决方案


推荐阅读