|
1 | | -# SolrNET5WebAPI |
2 | | - How to connect Solr with .NET5 |
| 1 | +# How to connect Solr with .NET5 |
| 2 | + |
| 3 | +This is a very basic sample to show Solr & .NET5 integration. |
| 4 | + |
| 5 | +### Nuget Packages |
| 6 | +- SolrNet.Core |
| 7 | +- SolrNet.Microsoft.DependencyInjection |
| 8 | + |
| 9 | +### Init Solr Service in Startup.cs |
| 10 | + |
| 11 | +```csharp |
| 12 | +var credentials = Encoding.ASCII.GetBytes("username:password"); |
| 13 | +var credentialsBase64 = Convert.ToBase64String(credentials); |
| 14 | +services.AddSolrNet<WeatherForecast>("https://solr-server-ip:port/solr/name", options => |
| 15 | +{ |
| 16 | + options.HttpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", credentialsBase64); |
| 17 | +}); |
| 18 | +``` |
| 19 | + |
| 20 | +### Model |
| 21 | + |
| 22 | +```csharp |
| 23 | +public class WeatherForecast |
| 24 | +{ |
| 25 | + [SolrUniqueKey("id")] |
| 26 | + public string Id { get; set; } |
| 27 | + |
| 28 | + [SolrField("temperature")] |
| 29 | + public int Temperature { get; set; } |
| 30 | + |
| 31 | + [SolrField("summary")] |
| 32 | + public string Summary { get; set; } |
| 33 | +} |
| 34 | +``` |
| 35 | + |
| 36 | +### Api Controller |
| 37 | +```csharp |
| 38 | +private readonly ILogger<WeatherForecastController> _logger; |
| 39 | +private readonly ISolrOperations<WeatherForecast> _solr; |
| 40 | + |
| 41 | +public WeatherForecastController(ILogger<WeatherForecastController> logger, ISolrOperations<WeatherForecast> solr) |
| 42 | +{ |
| 43 | + _logger = logger; |
| 44 | + _solr = solr; |
| 45 | +} |
| 46 | +``` |
| 47 | + |
| 48 | +### Query |
| 49 | + |
| 50 | +```csharp |
| 51 | +[HttpGet] |
| 52 | +public async Task<IActionResult> QueryTemperatureAsync([FromQuery]string parameter) |
| 53 | +{ |
| 54 | + // sample |
| 55 | + // parameter = "Freezing"; |
| 56 | + _logger.LogInformation("Search: " + parameter); |
| 57 | + SolrQueryResults<WeatherForecast> results = await _solr.QueryAsync(new SolrQuery($"summary: {parameter}")); |
| 58 | + |
| 59 | + return Ok(results); |
| 60 | +} |
| 61 | +``` |
| 62 | + |
| 63 | +### Add |
| 64 | + |
| 65 | +```csharp |
| 66 | +[HttpPost] |
| 67 | +public async Task<IActionResult> AddTemperatureAsync([FromQuery]WeatherForecast weather) |
| 68 | +{ |
| 69 | + _logger.LogInformation("Add: " + weather.Summary); |
| 70 | + |
| 71 | + // sample |
| 72 | + //Random rng = new(); |
| 73 | + //WeatherForecast weather = new() |
| 74 | + //{ |
| 75 | + // Id = "1", |
| 76 | + // Summary = Summaries[rng.Next(Summaries.Length)], |
| 77 | + // Temperature = 10 |
| 78 | + //}; |
| 79 | +
|
| 80 | + await _solr.AddAsync(weather); |
| 81 | + await _solr.CommitAsync(); |
| 82 | + |
| 83 | + return Ok(weather); |
| 84 | +} |
| 85 | +``` |
| 86 | + |
| 87 | +### License |
| 88 | + |
| 89 | +React is [MIT licensed](./LICENSE). |
0 commit comments