2
Goodnight!
I’m studying about ASP.NET (I come from java) and I’m a little confused by all this.
I am trying to create an endpoint to return the client list of my database, however, I can not in any way initialize it!
When I run the project, it returns the following error
exceptionMessage":"The object has not yet been initialized. Ensure that HttpConfiguration.EnsureInitialized() is called in the application's startup
According to the examples I found, it’s all OK, I can’t find anything to help me with the error in question.
I would also like, if anyone knows any source of examples or tutorials, how to create an interface to interact between controller and bank actions!
Below are the project classes
Webconfig.Cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
}
}
Clientecontroller
public class ClienteController : ApiController
{
DbContext db = new DbContext();
[HttpGet]
[AllowAnonymous]
[Route("/{id:guid}", Name = "GetClientes")]
public IHttpActionResult GetClientes(int? id)
{
return Ok(this.db.clientes.Where(c => c.usuarioId == id).ToList());
}
[HttpGet]
[AllowAnonymous]
[Route("/id/{id:guid}", Name = "GetClienteById")]
public IHttpActionResult GetClienteById(int? id)
{
if (id == null)
{
ModelState.AddModelError("", "A Identificação do cliente é obrigatória.");
return BadRequest(ModelState);
}
return Ok(this.db.clientes.FindAsync(id));
}
}
Dbcontext
[DbConfigurationType(typeof(MySql.Data.Entity.MySqlEFConfiguration))]
public class DbContext : System.Data.Entity.DbContext
{
public DbContext()
: base("ResourceContext")
{
Configuration.ProxyCreationEnabled = false;
Configuration.LazyLoadingEnabled = false;
}
public static DbContext Create()
{
return new DbContext();
}
public DbSet<Cliente> clientes { get; set; }
}
Customer.Cs
public class Cliente
{
[Key]
public int Id { get; set; }
[Required]
public int usuarioId { get; set; } //Foreign Key
[Required]
[Display(Name = "Nome do Cliente")]
[MaxLength(200)]
public string Nome { get; set; }
[DataType(DataType.Date)]
[Display(Name = "Data de Nascimento")]
public DateTime dataNascimento { get; set; }
[MaxLength(100)]
public string email { get; set; }
[MaxLength(200)]
public string endereco { get; set; }
[MaxLength(13)]
public string telefone { get; set; }
[Required]
[MaxLength(14)]
public string celular { get; set; }
[Required]
[DataType(DataType.Date)]
[Display(Name = "Data de Cadastro")]
public DateTime dataCadastro { get; set; }
[Required]
public bool ativo { get; set; }
}
Startup.Cs
public class Startup
{
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
app.UseWebApi(config);
}
private void ConfigureOAuth(IAppBuilder app)
{
//Token Consumption
app.CreatePerOwinContext(DbContext.Create);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
}
in the following tutorial ( http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/ ) it does not use Global.asax.Cs, it is removed at the beginning of the tutorial, instead Startup.Cs is used to run the project
– Lucas Freitas