0

我是 Blazor 的新手,我创建了一个 API 控制器来处理我的 CRUD 例程。它有一个构造函数,因此我可以将与数据库的连接保存到私有成员。但是,当我的应用程序启动时,构造函数永远不会被调用。我也尝试向控制器发送一个 POST,但我收到了一个错误的请求,所以我假设它仍然没有正确设置。谢谢您的帮助!

启动.cs

    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
      if (env.IsDevelopment())
      {
        app.UseDeveloperExceptionPage();
        app.UseDatabaseErrorPage();
      }
      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.UseRouting();

      app.UseAuthentication();
      app.UseAuthorization();

      app.UseEndpoints(endpoints =>
      {
        endpoints.MapControllers();
        endpoints.MapBlazorHub();
        endpoints.MapFallbackToPage("/_Host");
      });

    }

PTSEventController.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using ComEd.PTS.DataStore.Models;
using Microsoft.AspNetCore.Mvc;

namespace ComEd.PTS.Event.UI.Controllers
{
  [Route("api/[controller]")]
  public class PTSEventController : ControllerBase
  {
    private readonly PeakTimeSavingsDBContext _dbContext;

    public PTSEventController(PeakTimeSavingsDBContext dbContext)
    {
      _dbContext = dbContext; //<<<< The constructor never gets called >>>>
    }

    // GET: api/<controller>
    [HttpGet]
    public IEnumerable<string> Get()
    {
      return new string[] { "value1", "value2" };
    }

    // GET api/<controller>/5
    [HttpGet("{id}")]
    public string Get(int id)
    {
      return "value";
    }

    // POST api/<controller>
    [HttpPost]
    public void Post([FromBody]string value)
    {
      int x = 0;
      x++;
    }

    // PUT api/<controller>/5
    [HttpPut("{id}")]
    public void Put(int id, [FromBody]string value)
    {
      int x = 0;
      x++;

    }

    // DELETE api/<controller>/5
    [HttpDelete("{id}")]
    public void Delete(int id)
    {
      int x = 0;
      x++;
    }
  }
}
4

1 回答 1

0

将您的课程添加为服务?

在 startup.cs 的 ConfigureServices() 中:

services.AddSingleton<PTSEventController>();
于 2020-03-02T06:50:18.390 回答