I have tried to follow this tutorial, but am unable to use a controller to read from my docker based couchbase server running at http://127.0.0.1:8091/. Am using Couchbase Server 6.6.0 on docker.
Here is my controller:
namespace CouchbaseWebApi.Controllers
{
using Couchbase;
using Couchbase.KeyValue;
using CouchbaseWebApi.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
[ApiController]
[Route("[controller]")]
public class RecordController : ControllerBase
{
private readonly ILogger<RecordController> _logger;
private IBucket _bucket;
private ICouchbaseCollection _collection;
public RecordController(ILogger<RecordController> logger, ITravelBucketProvider provider)
{
if (provider == null)
{
throw new ArgumentNullException(nameof(provider));
}
_logger = logger;
InitializeCluster(provider);
}
private async void InitializeCluster(ITravelBucketProvider provider)
{
_bucket = await provider.GetBucketAsync().ConfigureAwait(false);
_collection = await _bucket.DefaultCollectionAsync().ConfigureAwait(false);
if (_bucket == null)
{
throw new ArgumentNullException(nameof(_bucket));
}
if (_collection == null)
{
throw new ArgumentNullException(nameof(_collection));
}
}
[HttpPost]
[Route("/")]
public async void InsertRecord(CustomRecord record)
{
try
{
var key = Guid.NewGuid().ToString();
await _collection.InsertAsync(key, record);
_logger.LogInformation("Inserted record with ID: " + key);
}
catch (Exception ex)
{
_logger.LogError($"Could not insert record due to {ex.Message}");
}
}
}
}
I have provided the config in Startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllers();
services.AddSwaggerGen();
services.AddCouchbase(Configuration.GetSection("Couchbase"));
services.AddCouchbaseBucket<ITravelBucketProvider>("travel-sample");
}
Finally, I inherited the custom provider:
using Couchbase.Extensions.DependencyInjection;
namespace CouchbaseWebApi.Interfaces
{
public interface ITravelBucketProvider : INamedBucketProvider
{
}
}
The appsettings.json
contains:
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
}
},
"AllowedHosts": "*",
"Couchbase": {
"Servers": [ "http://127.0.0.1" ],
"Username": "Administrator",
"Password": "password"
}
}
When running this, I get null
when I try to resolve the bucket in the controller.
Have tried setting the server appsettings.json to http://127.0.0.1:8091
, http://localhost:8091
, http://127.0.0.1
, couchbase://localhost
and http://localhost
to no avail.
Please advise on how I can proceed. Was able to get a hold of the bucket when using the console app example, just not with a Web Api.