Skip to content

Instantly share code, notes, and snippets.

@matlus
Created March 10, 2019 16:21
Show Gist options
  • Select an option

  • Save matlus/e1b65ea12edb254ddea75fb0e061a6e3 to your computer and use it in GitHub Desktop.

Select an option

Save matlus/e1b65ea12edb254ddea75fb0e061a6e3 to your computer and use it in GitHub Desktop.
ASP.NET Core (2.2) Web API by hand
/*
* Create a new Empty ASP.NET Core project
* Replace the entire Startup class (not the namespace) with the code below
*/
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.Run(async (context) =>
{
var path = context.Request.Path;
if (path.StartsWithSegments(new PathString("/movies"), StringComparison.OrdinalIgnoreCase))
{
await MatlusMvc.ProcessRequest(context);
}
else
{
await context.Response.WriteAsync("Hello World!");
}
});
}
}
internal sealed class MatlusMvc
{
public static async Task ProcessRequest(HttpContext context)
{
var pathString = context.Request.Path;
var controller = CreateController(pathString);
await controller.ProcessRequest(context);
}
private static ControllerBase CreateController(PathString pathString)
{
if (pathString.StartsWithSegments("/movies", StringComparison.OrdinalIgnoreCase))
{
return new MoviesController();
}
throw new ControllerNotFoundException($"No Controller found for the PathString: " + pathString);
}
}
internal abstract class ControllerBase
{
public async Task ProcessRequest(HttpContext context)
{
await ProcessRequestCore(context);
}
protected abstract Task ProcessRequestCore(HttpContext context);
}
internal sealed class MoviesController : ControllerBase
{
#region Movies
private static readonly List<Movie> AllMovies = new List<Movie>
{
new Movie("Star Wars Episode IV: A New Hope", "StarWarsEpisodeIV.jpg", "Sci-Fi", 1977),
new Movie("Star Wars Episode V: The Empire Strikes Back", "StarWarsEpisodeV.jpg", "Sci-Fi", 1980),
new Movie("Star Wars Episode VI: Return of the Jedi", "StarWarsEpisodeVI.jpg", "Sci-Fi", 1983),
new Movie("Star Wars: Episode I: The Phantom Menace", "StarWarsEpisodeI.jpg", "Sci-Fi", 1999),
new Movie("Star Wars Episode II: Attack of the Clones", "StarWarsEpisodeII.jpg", "Sci-Fi", 2002),
new Movie("Star Wars: Episode III: Revenge of the Sith", "StarWarsEpisodeIII.jpg", "Sci-Fi", 2005),
new Movie("Olympus Has Fallen", "Olympus_Has_Fallen_poster.jpg", "Action", 2013),
new Movie("G.I. Joe: Retaliation", "GIJoeRetaliation.jpg", "Action", 2013),
new Movie("Jack the Giant Slayer", "jackgiantslayer4.jpg", "Action", 2013),
new Movie("Drive", "FileDrive2011Poster.jpg", "Action", 2011),
new Movie("Sherlock Holmes", "FileSherlock_Holmes2Poster.jpg", "Action", 2009),
new Movie("The Girl with the Dragon Tatoo", "FileThe_Girl_with_the_Dragon_Tattoo_Poster.jpg", "Drama", 2011),
new Movie("Saving Private Ryan", "SavingPrivateRyan.jpg", "Drama", 1998),
new Movie("Schindlers List", "SchindlersList.jpg", "Drama", 1993),
new Movie("Good Will Hunting", "FileGood_Will_Hunting_theatrical_poster.jpg", "Drama", 1997),
new Movie("Citizen Kane", "Citizenkane.jpg", "Drama", 1941),
new Movie("Shawshank Redemption", "FileShawshankRedemption.jpg", "Drama", 1994),
new Movie("Forest Gump", "ForrestGump.jpg", "Drama", 1994),
new Movie("We Bought a Zoo", "FileWe_Bought_a_Zoo_Poster.jpg", "Drama", 2011),
new Movie("A Beautiful Mind", "FileAbeautifulmindposter.jpg", "Drama", 2001),
new Movie("Avatar", "Avatar.jpg", "Sci-Fi", 2009),
new Movie("Iron Man", "IronMan.jpg", "Sci-Fi", 2008),
new Movie("Terminator 2", "Terminator2.jpg", "Sci-Fi", 1991),
new Movie("The Dark Knight", "TheDarkKnight.jpg", "Sci-Fi", 2001),
new Movie("The Matrix", "TheMatrix.jpg", "Sci-Fi", 1999),
new Movie("Transformers", "Transformers.jpg", "Sci-Fi", 2007),
new Movie("Revenge Of The Fallen", "TransformersRevengeOfTheFallen.jpg", "Sci-Fi", 2009),
new Movie("The Dark of the Moon", "TransformersTheDarkoftheMoon.jpg", "Sci-Fi", 2011),
new Movie("X-Men First Class", "XMenFirstClass.jpg", "Sci-Fi", 2011),
new Movie("Snitch", "Snitch.jpg", "Thriller", 2013),
new Movie("Life Of Pi", "LifeOfPi.jpg", "Drama", 2012),
new Movie("The Call", "TheCall.jpg", "Thriller", 2013),
new Movie("Wake in Fright", "WakeInFright.jpg", "Thriller", 1971),
new Movie("Oblivion", "Oblivion.jpg", "Sci-Fi", 2013),
new Movie("American Sniper", "AmericanSniper.jpg", "Thriller", 2015),
new Movie("Run All Night", "RunAllNight.jpg", "Thriller", 2015),
new Movie("Mission: Impossible - Rogue Nation", "MissionImpossibleRogueNation.jpg", "Thriller", 2015),
new Movie("Spectre", "Spectre.jpg", "Thriller", 2015),
new Movie("Insurgent", "Insurgent.jpg", "Thriller", 2015),
new Movie("Kill Me Three Times", "KillMeThreeTimes.jpg", "Thriller", 2014),
new Movie("Batman v Superman: Dawn of Justice", "BatmanVSupermanDawnofJustice.jpg", "Action", 2016),
new Movie("Avengers: Age of Ultron", "AvengersAgeofUltron.jpg", "Action", 2015),
new Movie("Guardians of the Galaxy", "GuardiansoftheGalaxy.jpg", "Action", 2015),
new Movie("Kingsman: The Secret Service", "KingsmanTheSecretService.jpg", "Action", 2014),
new Movie("Seventh Son", "SeventhSon.jpg", "Action", 2014),
new Movie("Maze Runner: The Scorch Trials", "MazeRunnerTheScorchTrials.jpg", "Thriller", 2015),
};
private static readonly List<MovieWithCategory> MoviesWithCategories = AllMovies.Select(m => new MovieWithCategory { Title = m.Title, Category = m.Category }).OrderBy(m => m.Category).ToList();
private static readonly List<MovieWithYear> MoviesWithYears = AllMovies.Select(m => new MovieWithYear { Title = m.Title, Year = m.Year }).OrderBy(m => m.Year).ToList();
private static readonly List<MovieWithImageUrl> MoviesWithImageUrls = AllMovies.Select(m => new MovieWithImageUrl { Title = m.Title, ImageUrl = m.ImageUrl }).OrderBy(m => m.ImageUrl).ToList();
#endregion Movies
protected override async Task ProcessRequestCore(HttpContext context)
{
var pathString = context.Request.Path;
pathString.StartsWithSegments("/movies", StringComparison.OrdinalIgnoreCase, out var matched, out var remaining);
IEnumerable<Movie> movies = null;
if (!remaining.HasValue || remaining.Value == "/")
{
movies = GetAllMovies();
}
else if (remaining.StartsWithSegments("/category", StringComparison.OrdinalIgnoreCase, out var remainingCategory))
{
movies = MoviesByGenre(remainingCategory.Value.Substring(1));
}
else if (remaining.StartsWithSegments("/year", StringComparison.OrdinalIgnoreCase, out var remainingYear))
{
movies = MoviesByGenre(remainingYear.Value.Substring(1));
}
var jsonString = JsonConvert.SerializeObject(movies);
context.Response.StatusCode = (int)HttpStatusCode.OK;
context.Response.ContentType = "application/json";
context.Response.ContentLength = jsonString.Length;
await context.Response.WriteAsync(jsonString);
}
private IEnumerable<Movie> GetAllMovies()
{
return AllMovies;
}
private IEnumerable<Movie> MoviesByGenre(string category)
{
return AllMovies.Where(m => string.Compare(m.Category, category, StringComparison.OrdinalIgnoreCase) == 0);
}
private IEnumerable<Movie> MoviesByYear(int year)
{
return AllMovies.Where(m => m.Year == year);
}
}
public sealed class Movie
{
public string Title { get; set; }
public string ImageUrl { get; set; }
public string Category { get; set; }
public int Year { get; set; }
public Movie()
{
}
public Movie(string title, string imageUrl, string category, int year)
{
Title = title;
ImageUrl = imageUrl;
Category = category;
Year = year;
}
}
public sealed class MovieWithCategory
{
public string Title { get; set; }
public string Category { get; set; }
}
public sealed class MovieWithYear
{
public string Title { get; set; }
public int Year { get; set; }
}
public sealed class MovieWithImageUrl
{
public string Title { get; set; }
public string ImageUrl { get; set; }
}
[Serializable]
internal sealed class ControllerNotFoundException : Exception
{
public ControllerNotFoundException()
{
}
public ControllerNotFoundException(string message) : base(message)
{
}
public ControllerNotFoundException(string message, Exception innerException) : base(message, innerException)
{
}
private ControllerNotFoundException(SerializationInfo info, StreamingContext context) : base(info, context)
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment