Created
October 3, 2024 16:10
-
-
Save amantix/c7c8f2a5ffedb6b188f9c0650bc8697a to your computer and use it in GitHub Desktop.
Simple web api example using aspnet core
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Microsoft.AspNetCore.Mvc; | |
namespace WebApplication1; | |
public class Program | |
{ | |
public static void Main(string[] args) | |
{ | |
var builder = WebApplication.CreateBuilder(args); | |
// Add services to the container. | |
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle | |
builder.Services.AddEndpointsApiExplorer(); | |
builder.Services.AddSwaggerGen(); | |
builder.Services.AddControllers(); | |
var app = builder.Build(); | |
// Configure the HTTP request pipeline. | |
if (app.Environment.IsDevelopment()) | |
{ | |
app.UseSwagger(); | |
app.UseSwaggerUI(); | |
} | |
app.MapControllers(); | |
app.Run(); | |
} | |
} | |
public class WeatherForecast | |
{ | |
public DateOnly Date { get; set; } | |
public int TemperatureC { get; set; } | |
public int TemperatureF => 32 + (int)(TemperatureC / 0.5556); | |
public string? Summary { get; set; } | |
} | |
[ApiController] | |
[Route("[controller]")] | |
public class WeatherForecastController : ControllerBase | |
{ | |
private string[] summaries = new[] | |
{ | |
"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching" | |
}; | |
[HttpGet] | |
public ActionResult<WeatherForecast[]> GetForecast() | |
{ | |
var forecast = Enumerable.Range(1, 5).Select(index => | |
new WeatherForecast | |
{ | |
Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)), | |
TemperatureC = Random.Shared.Next(-20, 55), | |
Summary = summaries[Random.Shared.Next(summaries.Length)] | |
}) | |
.ToArray(); | |
return forecast; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment