Skip to content

Instantly share code, notes, and snippets.

@ripesunflower
Created September 24, 2018 08:51
Show Gist options
  • Save ripesunflower/f150d57f17b8eaaec9b34d30de4d9cfe to your computer and use it in GitHub Desktop.
Save ripesunflower/f150d57f17b8eaaec9b34d30de4d9cfe to your computer and use it in GitHub Desktop.
public interface ICatalogue
{
int Id { get; set; }
string Name { get; set; }
}
public abstract class BaseEnumController<TEnum, TViewModel> : Controller
where TEnum : struct, IConvertible, IFormattable
where TViewModel : class, ICatalogue, new()
{
[HttpGet]
public IEnumerable<TViewModel> GetMany(string contentName)
{
var totalItemCount = Enum.GetValues(typeof(TEnum)).Length;
var items = Enum.GetValues(typeof(TEnum))
.Cast<TEnum>()
.Select(e => new TViewModel
{
Id = (int)(object)e,
Name = e.GetType()
.GetMember(e.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
.GetName()
});
HttpContext.Response.AddContentRangeHeader(
contentName,
new PagingOptions(0, totalItemCount),
totalItemCount);
return items;
}
[HttpGet("{id}")]
public IActionResult GetOne([FromRoute] int id)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
if (!Enum.IsDefined(typeof(TEnum), id))
{
return NotFound();
}
var enumValue = (TEnum)(object)id;
var condition = new TViewModel
{
Id = id,
Name = enumValue.GetType()
.GetMember(enumValue.ToString())
.First()
.GetCustomAttribute<DisplayAttribute>()
.GetName()
};
return Ok(condition);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment