Creating an Web api using Asp.net core. The endpoint I'm creating will return a list of all the customers (currently I've only seeded the DB with 1 customer). When I perform a GET request from Postman I get a "Could not get any Response". When I navigate to that endpoint via Chrome I see the response but the json returned seems to be missing brackets.
[
{
"customerId":1,
"firstName":"John",
"lastName":"Doe",
"email":"johndoe@email.com",
"address": {
"addressId":1,
"addressLine1":"2119 Some street",
"addressLine2":null,
"locality":"New York",
"region":"New York",
"country":"USA",
"postCode":"10005",
"customerId":1
I'm wondering if the poorly formatted Json response is the reason Postman isn't working. I'd like to understand whats wrong. Is there something I'm doing wrong in my simple example that could be causing me this headache.
My repository:
public class LodgingRepository : ILodgingRepository
{
private readonly LodgingCrmContext _context;
public LodgingRepository( LodgingCrmContext context )
{
_context = context;
}
public async Task<IEnumerable<Customer>> GetCustomersAsync( )
{
return await _context.Customers
.Include( c => c.Address )
.ToListAsync( );
}
}
My Controller
[Route( "api/customers" )]
public class CustomerController : Controller
{
private readonly ILodgingRepository _lodgingRepository;
public CustomerController( ILodgingRepository lodgingRepository )
{
_lodgingRepository = lodgingRepository;
}
[HttpGet]
public async Task<IActionResult> GetCustomersAsync( )
{
return Ok( await _lodgingRepository.GetCustomersAsync( ) );
}
}
StartUp
public void ConfigureServices( IServiceCollection services )
{
services.AddMvc( ).AddMvcOptions( options =>
options.OutputFormatters.Add( new XmlDataContractSerializerOutputFormatter( ) ) );
services.AddDbContext<LodgingCrmContext>( options =>
options.UseSqlServer( Configuration.GetConnectionString( "DefaultConnection" ) ) );
services.AddScoped<ILodgingRepository, LodgingRepository>( );
}
public void Configure( IApplicationBuilder app, IHostingEnvironment env, LodgingCrmContext lodgingCrmContext )
{
if( env.IsDevelopment( ) )
{
app.UseDeveloperExceptionPage( );
}
app.UseMvc( );
app.Run( async ( context ) => { await context.Response.WriteAsync( "Hello World!" ); } );
}
Address Entity
public class Address
{
[Key]
[DatabaseGenerated( DatabaseGeneratedOption.Identity )]
public int AddressId { get; set; }
[Required]
[MaxLength( 254 )]
public string AddressLine1 { get; set; }
[MaxLength( 254 )]
public string AddressLine2 { get; set; }
[Required]
[MaxLength( 60 )]
public string Locality { get; set; }
[Required]
[MaxLength( 50 )]
public string Region { get; set; }
[Required]
[MaxLength( 60 )]
public string Country { get; set; }
[Required]
[MaxLength( 9 )]
public string PostCode { get; set; }
[ForeignKey( nameof(CustomerId) )]
public int CustomerId { get; set; }
public Customer Customer { get; set; }
}