Saturday, March 19, 2022

ASP.NET Core MVC (.NET 6)

1. appsettings.json:

"ConnectionStrings": {
    "DefaultConnection": "Persist Security Info=False;User ID=sa;password=1234;Initial Catalog=ProdDB; Data Source=ASHRAFUL-IT\\SQL2017;Connection Timeout=100000;"
  }

2. Install Nuget Package:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
Microsoft.EntityFrameworkCore.Tools
Microsoft.EntityFrameworkCore.Design

3. Application DB Context:

public class ApplicationDBContext : DbContext
    {
        public ApplicationDBContext(DbContextOptions<applicationdbcontext> options)
        : base(options)
        {
        }
        public DbSet<productinfo> ProductInfos { get; set; }
    }
          
4. Programm.cs/Startup.cs:
          
   // Add services to the container.
builder.Services.AddControllersWithViews()
      .AddJsonOptions(options =&gt;
      {
          options.JsonSerializerOptions
         .PropertyNamingPolicy = null;
      });


builder.Services.AddDbContext<ApplicationDBContext>(dbContextOption => dbContextOption.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));
builder.Services.AddScoped<IProductRepository, ProductService>();

===================================================
startup.cs:
public class Startup
    {
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }

        public IConfiguration Configuration { get; }
        readonly string MyAllowSpecificOrigins = "_myAllowSpecificOrigins";

        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {

            services.AddControllers();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo { Title = "CRUDDotNet5", Version = "v1" });
            });
            services.AddDbContext<ProductDbContext>
                (item=>item.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddScoped<IProductRepository, ProductsRepository>();

            services.AddCors(options =>
            {
                options.AddPolicy(name: MyAllowSpecificOrigins,
                                  builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader()
                                   );
            });


            services.AddMvc().AddJsonOptions(o =>
            {
                o.JsonSerializerOptions.PropertyNamingPolicy = null;
                o.JsonSerializerOptions.DictionaryKeyPolicy = null;
            });

        }

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseSwagger();
                app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "CRUDDotNet5 v1"));
            }



            app.UseHttpsRedirection();

            app.UseRouting();

            app.UseCors(MyAllowSpecificOrigins);

            app.UseAuthorization();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
        }
    }
=========================================================
          

5. Create Model :
    public class ProductInfo
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ProdId { get; set; }
        public string ProdName { get; set; }
        public decimal ProdPrice { get; set; }
    }

          
6. Repository:
          IProductRepository
          ProductService
          
    public interface IProductRepository
    {
        List<productinfo> GetProductInfos();
    }   
          
    public class ProductService : IProductRepository
    {
        public ApplicationDBContext _applicationDBContext;
        public ProductService(ApplicationDBContext applicationDBContext)
        {
            _applicationDBContext = applicationDBContext;
        }

        public List<productinfo> GetProductInfos()
        {
          return  _applicationDBContext.ProductInfos.ToList();
        }
    }     
          
7. Product Controller:
    public class ProductController : Controller
    {
        IProductRepository _productRepository ;

        public ProductController(IProductRepository productRepository)
        {
            _productRepository = productRepository;
        }


        public IActionResult Index()
        {
            return View();
        }

        public IActionResult GetProductInfos()
        {
            var res = _productRepository.GetProductInfos();
            return Ok(Json(res));
        }
    }
          
          

No comments:

Post a Comment

JWT Authentication in ASP.NET Core Web API

  In this tutorial we'll go through a simple example of how to implement  JWT (JSON Web Token) authentication in an ASP.NET Core 3.0 API...