Ensure that HttpConfiguration.EnsureInitialized ()

2

Good Night!

I'm studying ASP.NET (I come from java) and I'm a bit confused by all that.

I'm trying to create an endpoint to return the list of clients from my database, however, I can not initialize it at all!

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, everything is Ok, I can not find anything to help me with the error in question.

I would also like, if anyone knows of any source of examples or tutorials, how to create an Interface to interact between the actions of the controller and the bank!

Below is 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();
    }
}

ClientController

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; }
}

Client.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());
    }
}
    
asked by anonymous 28.10.2015 / 00:58

1 answer

0

The most important file missing: Global.asax.cs .

Anyway, this is a classic Web API error. In Web API 2, the global configuration log changed shape. In the file Global.asax.cs of the root directory, Application_Start event, change:

WebApiConfig.Register(GlobalConfiguration.Configuration);

By:

GlobalConfiguration.Configure(WebApiConfig.Register);

You can also optionally force execution on the following as the last line of Application_Start :

GlobalConfiguration.Configuration.EnsureInitialized(); 
    
28.10.2015 / 04:29