Ricker Silva
Ricker Silva

Reputation: 1135

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

I'm making a PoC for a search functionality. 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.

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. So I created a new one called 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

http://localhost:52457/api/search/

it says the page does not work, error 500, in chrome.

Update 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. 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

Upvotes: 0

Views: 2664

Answers (1)

Ricker Silva
Ricker Silva

Reputation: 1135

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

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

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

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. like this

Controller constructor

    private readonly MyDbContext _context;

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

Upvotes: 1

Related Questions