Created
September 24, 2018 08:51
-
-
Save ripesunflower/f150d57f17b8eaaec9b34d30de4d9cfe to your computer and use it in GitHub Desktop.
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
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