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
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
relatoria_BuscadorContextto the dependency injection?Startup.cs-public void Configure(..) { app.UseDeveloperExceptionPage(); }.