I'm using DTO library shared between server and client.
Example DTOLib:
public class BaseDTO
{
public int Id {get;set;}
public string SharedProperty { get; set; }
}
public class BookDTO: BaseDTO
{
public const string ApiPath = "api/books"
public string IndividualProperty { get; set; }
}
public class NewsPapaerDTO: BaseDTO
{
public const string ApiPath = "api/newspapers"
public string IndividualProperty { get; set; }
}
I have individual webapi controller for each data type:
Example Asp.NetWebAPI:
[RoutePrefix(BookDTO.ApiPath)]
public class BookController: WebApiController
{
[Route("{id}")]
[HttpGet]
public BookDTO GetById (int id)
{
// db or service operation
return new BookDTO ();
}
[Route("list")]
[HttpGet]
public IEnumerable<BookDTO> GetAll ()
{
// db or service operation
return new List<BookDTO>();
}
[Route("find/{name}")]
[HttpGet]
public BookDTO FindByName(string name)
{
// db or service operation
return new List<BookDTO>();
}
}
In my client I'm using generic methods like: Example Asp.NetWebAPI:
private const string BASE_URI = "http://localhost:36417";
public T GetItemById<T>(string id) where T : BaseDTO, new ()
{
var clsType = typeof(T);
var pathField = clsType.GetField("ApiPath");
var pathFieldvalue = (string)pathField.GetRawConstantValue();
HttpWebRequest request = WebRequest.CreateHttp($"{BASE_URI}/{pathFieldvalue}/{id}");
var stream = request.GetResponse().GetResponseStream();
string data = "";
using (StreamReader sr = new StreamReader(stream))
{
data = sr.ReadToEnd();
}
return JsonConvert.DeserializeObject<T>(data);
}
catch (Exception)
{
throw;
}
finally { }
}
And finally in my client code I'm using: Client code:
var book = GetItemById<BookDTO>(1);
var newspaper = GetItemById<NewsPapaerDTO>(2);
Anyone have suggestions how to beautify this?
public const string ApiPath = "api/books" // looks ugly I think
maybe some kind of mapper library?
I want to keep client and server DTOs paths associated.
Aucun commentaire:
Enregistrer un commentaire