简体   繁体   English

asp.net核心Web API控制器停止响应并出现错误500

[英]asp.net core Web API controller stop responding with error 500

I'm making a PoC for a search functionality. 我正在为搜索功能设置PoC。 Ihave not done web API for a while and now Istarted from this tutorial and others, changing what I needed to for connecting my database and so on. 我已经有一段时间没有做过Web API了,现在我从本教程和其他教程开始 ,更改了连接数据库所需的内容,依此类推。

This is one of those things that worked on friday, and on monday morning it just don't. 这是星期五起作用的事情之一,而在星期一早晨却没有起作用。

I have created a web API project which has a valuesController already scaffolded. 我已经创建了一个Web API项目,该项目已经具有一个valuesController。 So I created a new one called searchController. 因此,我创建了一个名为searchController的新对象。 I wrotea method that simply returned a string and looked like this: 我写了一个方法,该方法只是返回一个字符串,看起来像这样:

[Produces("application/json")]
[Route("api/Search")]
public class SearchController : Controller
{
    private readonly DbContext _context;

    public SearchController(DbContext context)
    {
        _context = context;
    }

    // GET api/Search/search criteria
    [HttpGet("{q}")]
    public string Search(string q)
    {
        return $"this will be your answer to: {q}";
    }
}

I don't know why it worked and why it is not working now. 我不知道它为什么起作用,为什么现在不起作用。 I have changed it to look exactly as the values controller which I post below. 我将其更改为与下面发布的值控制器完全相同。

Values Controller 价值观控制器

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

namespace AbAeterno.Controllers
{
    [Route("api/[controller]")]
    public class ValuesController : Controller
    {
        // GET api/values
        [HttpGet]
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

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

        // POST api/values
        [HttpPost]
        public void Post([FromBody]string value)
        {
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody]string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }
    }
}

and Search Controller 和搜索控制器

    using AbAeterno.Models;
using Microsoft.AspNetCore.Mvc;

namespace AbAeterno.Controllers
{
    [Route("api/[controller]")]
    public class SearchController : Controller
    {
        private readonly DbContext _context;

        public SearchController(DbContext context)
        {
            _context = context;
        }

        // GET api/Search/search criteria
        [HttpGet]
        public string Get()
        {
            return "this method is alive";
        }
    }
}

When I run the solution, the default controller is values and it is working, when I changed url to 当我运行解决方案时,默认控制器是值,并且在将url更改为

http://localhost:52457/api/search/ HTTP://本地主机:52457 / API /搜索/

it says the page does not work, error 500, in chrome. 表示网页无法正常运行,错误是500,位于Chrome浏览器中。

Update startup.cs 更新startup.cs

I have found two ways of registering connection string, I wrote both but the second one, using DI, does not work as expected and when calling database, connection string is null. 我发现了两种注册连接字符串的方法,我都写了这两种方法,但是第二种方法使用DI不能按预期工作,并且在调用数据库时,连接字符串为null。 This is how I have it. 这就是我的方式。

  public void ConfigureServices(IServiceCollection services)
        {
            //Configure DB connection strings
            DbContext.ConnectionString = Configuration.GetConnectionString("DatabaseEF");

            //services.AddDbContext<DbContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("DatabaseEF")));


            // Add framework services.
            services.AddMvc();
        }

Solution

I removed the constructor and private variable and it worked again, as suggested by @Yuri S 我删除了构造函数和私有变量,然后再次工作,如@Yuri S所建议

Although there is a solution section in the question, that one is not considering Dependency Injection and should be taken as a temporary one. 尽管问题中有一个解决方案部分,但该部分并未考虑依赖注入,因此应将其视为临时解决方案。

If you want to use dependency injection, your files should look like this: 如果要使用依赖项注入,则文件应如下所示:

Db Context Db上下文

public partial class MyDbContext : DbContext
{
    public virtual DbSet<Table> Table { get; set; }

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

Startup.cs Startup.cs

    public void ConfigureServices(IServiceCollection services)
    {
        //Configure DB connection strings
        services.AddDbContext<MyDbContext>(opt => opt.UseSqlServer(Configuration.GetConnectionString("MyDbEF")));

        // Add framework services.
        services.AddMvc();
    }

With those two changes your connection string is registered in the DI manager components, so you can create a constructor in your controller that receives, injected, the context object configured with your connection string. 通过这两个更改,您的连接字符串将注册到DI管理器组件中,因此您可以在控制器中创建一个构造函数,该构造函数接收注入的,用您的连接字符串配置的上下文对象。 like this 像这样

Controller constructor 控制器构造函数

    private readonly MyDbContext _context;

    public SearchController(MyDbContext context)
    {
        _context = context;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM