Ninject Not working in ashx - asp.net

Ninject implementation works perfectly in WebForms. But due to some reasons it does not work in ashx.
My Code is below.
public class AllPlayers : HttpTaskAsyncHandler
{
[Inject]
public IUser _user { get; set; }
public AllPlayers(IUser user)
{
_user = user;
}
public AllPlayers()
{
}
public override async Task ProcessRequestAsync(HttpContext context)
{
var data = await _user.GetAllPlayers();
}
public bool IsReusable
{
get
{
return false;
}
}
}
Am I missing something ?

Related

query data by ID in ASP.Net MVC Core 6

I am trying to query the Product object from the database by using the ID. However, there was no data being sent to the View. I suspect that there is a problem with my Services and ProductController. I have try to use different methods to query the data
in the ProductServices file but none of them seems to work. Currently I don't know where the problem is.
Below is my code for the ProductService
using Microsoft.EntityFrameworkCore;
namespace e_commerce.Data.Services
{
public class ProductService : IProductService
{
private readonly ShopDbContext _context;
public ProductService(ShopDbContext context)
{
_context = context;
}
public void AddProduct(Product product)
{
_context.Products.Add(product);
_context.SaveChanges();
}
public IEnumerable<Product> GetProducts()
{
return _context.Products.ToList();
}
public void RemoveProduct(Product product)
{
throw new NotImplementedException();
}
public Product UpdateProduct(Product product)
{
throw new NotImplementedException();
}
public Product GetProductById(int id)
{
return _context.Products.FirstOrDefault(x => x.ProductID == id);
}
}
}
Here is my code for ProductController
using e_commerce.Data.Services;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
namespace e_commerce.Controllers
{
public class ProductController : Controller
{
private readonly IProductService _service;
public ProductController(IProductService service)
{
_service = service;
}
public ActionResult Index()
{
return View(_service.GetProducts());
}
public ActionResult Create()
{
return View();
}
[HttpPost]
public IActionResult Create([Bind("ProductImageUrl, ProductName, ProductPrice")]Product product)
{
if (ModelState.IsValid)
{
return View(product);
}
_service.AddProduct(product);
return RedirectToAction(nameof(Index));
}
public IActionResult Details(int id)
{
var products = _service.GetProductById(id);
return View();
}
}
}
Thank you for your help.
the problem is that you are not passing data with a view
public IActionResult Details(int id)
{
var product = _service.GetProductById(id);
if (product==null) product= new Product();
return View(product);
}

asp core web api http post is null

I created a webapi by looking at the ms basic documentation.
ms Doc
it was work
todoitems
Besides todoitems I
Because I wanted to use it in the form of Avatar Chart
Insert the model Avatarchart, create Avatarchartcontext, and make the controller as a scaffold.
solution view
However, when I tried to receive data as a post, the data always came in null.
error
null
this is code
[Route("api/AvatarCharts")]
[ApiController]
public class AvatarChartsController : ControllerBase
{
private readonly AvatarChartContext _context;
public AvatarChartsController(AvatarChartContext context)
{
_context = context;
}
// GET: api/AvatarCharts
[HttpGet]
public async Task<ActionResult<IEnumerable<AvatarChart>>> GetAvatarCharts()
{
return await _context.AvatarCharts.ToListAsync();
}
// GET: api/AvatarCharts/5
[HttpGet("{modelId}")]
public async Task<ActionResult<AvatarChart>> GetAvatarChart(long modelId)
{
var avatarChart = await _context.AvatarCharts.FindAsync(modelId);
if (avatarChart == null)
{
return NotFound();
}
return avatarChart;
}
// PUT: api/AvatarCharts/5
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPut("{modelId}")]
public async Task<IActionResult> PutAvatarChart(long modelId, AvatarChart avatarChart)
{
if (modelId != avatarChart.modelId)
{
return BadRequest();
}
_context.Entry(avatarChart).State = EntityState.Modified;
try
{
await _context.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!AvatarChartExists(modelId))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
// POST: api/AvatarCharts
// To protect from overposting attacks, see https://go.microsoft.com/fwlink/?linkid=2123754
[HttpPost]
public async Task<ActionResult<AvatarChart>> PostAvatarChart( AvatarChart avatarChart)
{
_context.AvatarCharts.Add(avatarChart);
await _context.SaveChangesAsync();
return CreatedAtAction("GetAvatarChart", new { modelId = avatarChart.modelId }, avatarChart);
}
// DELETE: api/AvatarCharts/5
[HttpDelete("{modelId}")]
public async Task<IActionResult> DeleteAvatarChart(long modelId)
{
var avatarChart = await _context.AvatarCharts.FindAsync(modelId);
if (avatarChart == null)
{
return NotFound();
}
_context.AvatarCharts.Remove(avatarChart);
await _context.SaveChangesAsync();
return NoContent();
}
private bool AvatarChartExists(long modelId)
{
return _context.AvatarCharts.Any(e => e.modelId == modelId);
}
}
public class AvatarChartContext :DbContext
{
public AvatarChartContext(DbContextOptions<AvatarChartContext> options) : base(options)
{
}
public DbSet<AvatarChart> AvatarCharts { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<AvatarChart>().HasKey(c => c.modelId);
}
}
public class AvatarChart
{
[Key]
public long modelId;
public string colorCode;
public long dateTime; //ex 20210101130000
public string name;
public string diagnose;
}
swagger
add postgressql dbenter image description here
Update:
You missed the {get; set;}.
public class AvatarChart
{
[Key]
public long modelId {get; set;}
public string colorCode {get; set;}
public long dateTime {get; set;} //ex 20210101130000
public string name {get; set;}
public string diagnose {get; set;}
}
Can you make these changes and tell me what value is being returned on the variable result. Also, can you validate your ModelState first?
[HttpPost]
public async Task<ActionResult> PostAvatarChart( AvatarChart avatarChart)
{
await _context.AvatarCharts.AddAsync(avatarChart);
var result = await _context.SaveChangesAsync() > 0;
return CreatedAtAction("GetAvatarChart", new { modelId = avatarChart.modelId }, avatarChart);
}

Asp.Net webapi : throw new RestException(HttpStatusCode.Unauthorized)

I am a beginner developer and I have an issue in Query handler when using throw new RestException(HttpStatusCode.Unauthorized)
this is my query handler:
namespace Application.User
{
public class Login
{
public class Query : IRequest<AppUser>
{
public string Email { get; set; }
public string Password { get; set; }
}
public class QueryValidator : AbstractValidator<Query>
{
public QueryValidator()
{
RuleFor(x => x.Email).NotEmpty();
RuleFor(x => x.Password).NotEmpty();
}
}
public class Handler : IRequestHandler<Query, AppUser>
{
private readonly UserManager<AppUser> _userManager;
private readonly SignInManager<AppUser> _signUserManager;
public Handler(UserManager<AppUser> userManager, SignInManager<AppUser> signInManager)
{
_userManager = userManager;
_signUserManager = signInManager;
}
public async Task<AppUser> Handle(Query request, CancellationToken cancellationToken)
{
var user = await _userManager.FindByEmailAsync(request.Email);
if (user == null)
throw new RestException(HttpStatusCode.Unauthorized);
var result = await _signUserManager.CheckPasswordSignInAsync(user, request.Password, false);
if (result.Succeeded)
{
//TODO : generate token
return user;
}
throw new RestException(HttpStatusCode.Unauthorized);
}
}
}
}

How create API using repository pattern in dotnet core

Here is my code and I want to create API, from the repository methods.
This is Entity table of my code:
public partial class Course
{
public int ID { get; set; }
public string Name { get; set; }
public int DepartmentID { get; set; }
[ForeignKey("DepartmentID")]
public virtual Department Department { get; set; }
public int GradeLevelsID { get; set; }
[ForeignKey("GradeLevelsID")]
public virtual GradeLevels GradeLevels { get; set; }
// Navigation
public virtual ICollection<Units> Units { get; set; }
}
I need some output according to the methods:
Create course for the particular Gradelevel
Get Course of the GradeLevel
Get All Unit of the course
I write code for the following condition in the IRepository
Public interface ICourseRepository
{
Task<Course> GetAllCourseByGradeLevleId(int id)
Task<Course> UpdateCoursetAsync(int Id);
Task<Action> CreateCourseAsync(Course Course);
Task<Course> DeleteCourseAsync(int Id);
}
And the Repository Methods will be as following:
public class CountryRepository : ICourseRepository
{
public Task<Action> CreateCourseAsync(Course Course)
{
throw new NotImplementedException();
}
public Task<Course> DeleteCourseAsync(int Id)
{
throw new NotImplementedException();
}
public Task<Course> GetAllCourseByGradeLevleId(int id)
{
throw new NotImplementedException();
}
public Task<Course> UpdateCoursetAsync(int Id)
{
throw new NotImplementedException();
}
My Problem is that I am unable to write return type method and unable to fetch data from the relational table, as well as unable to write POST and PUT api for this conditions.
Here is my controller class:
[Route("api/[controller]")]
[ApiController]
public class CourseController : ControllerBase
{
private readonly ICourseRepository _courseRespository;
public CourseController(ICourseRepository courseRespository)
{
_courseRespository = courseRespository;
}
[HttpGet]
public async Task<IEnumerable<Course>> Get()
{
return await _courseRespository.GetAllCourseAsync();
}
public async Task<ActionResult<Course>> GetId(int id)
{
var result = await _courseRespository.GetAllCourseByIdAsync(id);
if (result == null)
{
return NotFound();
}
return result;
}
[HttpPost]
public async Task<ActionResult> Post(Course course)
{
// _courseRespository.CreateCourseAsync();
// await _courseRespository.SaveChangesAsync();
return CreatedAtAction("GetId", new { id = course.ID }, course);
}
How can write PUT and POST in this condition.
Try having a code like below,
[Route("Course")]
public class CountryRepository : ICourseRepository
{
[Route("~/users/Create")]
[ResponseType(typeof(Course))]
[HttpPost]
public async Task<Action> CreateCourseAsync(Course Course)
{
return Request.CreateResponse(HttpStatusCode.OK, resultObj);
}
}

SignalR missing connection in HubCallerContext

Trying to do simple chat and sending user to the userTracker when he/she is connected
public override async Task OnConnectedAsync()
{
var user = Helper.GetUserInformationFromContext(Context);
await this.userTracker.AddUserAsync(Context.Connection, user);
await Clients.All.SendAsync("UsersJoined", new UserInformation[] { user });
await Clients.All.SendAsync("SetUsersOnline", await GetOnlineUsersAsync());
await base.OnConnectedAsync();
}
but in the old versions HubCallerContext is like this :
public HubCallerContext(HubConnectionContext connection);
public HubConnectionContext Connection { get; }
public ClaimsPrincipal User { get; }
public string ConnectionId { get; }
the version I am using ( 2.3.0 ) is like
protected HubCallerContext();
public abstract string ConnectionId { get; }
public abstract string UserIdentifier { get; }
public abstract ClaimsPrincipal User { get; }
public abstract IFeatureCollection Features { get; }
public abstract CancellationToken ConnectionAborted { get; }
public abstract void Abort();
So how can I get the missing Connection ?
You simple have to inject it where you use it
Sample:
public class YourClassWhereYouNeedHubContext
{
// Inject into constructor
public YourClassWhereYouNeedHubContext (IHubContext<VarDesignHub> hubcontext)
{
HubContext = hubcontext;
...
}
private IHubContext<VarDesignHub> HubContext
{
get;
set;
}
}
Then you can also call
await this.HubContext.Clients.All.InvokeAsync("Completed", id);
Please read also:
Call SignalR Core Hub method from Controller

Resources