-1

I am trying to return data from tables using LINQ dependent on the login in user name to partial view using injection. but it fails. this is my method

 public  IEnumerable<CartView> SaveLater()
    {

        var model =  context.Orders.Where(a => a.User.UserName == User.Identity.Name)
            .Where(a => !context.Carts.Select(s => s.OrderId).Contains(a.Id))
            .Join(context.Products, order => order.ProductId, product => product.Id,
            (order, product) => new CartView
            {
                Name = product.Name,
                Amount = order.Amount,
                Description = product.Description,
                Image = product.Image,
                OrderId = order.Id,
                Price = product.Price
            }).AsEnumerable();
        return  model; 
    }

when I call the action in the browser route it runs ok, but when I run partial view this error is raised enter image description here

I made inject for the controller in the main view

@inject CartController savelater

this is my code to partial view

@{await Html.PartialAsync("../User/SaveLater", savelater.SaveLater()); }
  • Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Progman Feb 13 '22 at 15:57
  • No. Actually my action work well if i call it in the browser route, but when inject it to partial view raise this error. When i replace user. Identity. Name with static value it works well. – Mohamed Elmnegged Feb 13 '22 at 16:16
  • Please [edit] your question to include your source code as a working [mcve], which can be compiled and tested by others. – Progman Feb 13 '22 at 16:56
  • ok, so the user name is not set. You have to show the code that sets it in the working case and why that code doesnt work in this case – pm100 Feb 13 '22 at 17:49
  • how can i do that @pm100 – Mohamed Elmnegged Feb 13 '22 at 18:15
  • what is User.Identity, where does it come from, show the code that sets it up in the working case. – pm100 Feb 13 '22 at 18:25
  • the User.Identity is the default authentication and it should return the name Logged in user – Mohamed Elmnegged Feb 13 '22 at 18:30

1 Answers1

0

I replace User.Identity to

var userId = httpContextAccessor.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier).Value;

to get the userId and it works fine

also, add services to startup

 services.AddScoped<HttpContextAccessor>();

I follow the instruction from this link: https://www.koskila.net/how-to-get-current-user-in-asp-net-core/#Background-2