I'm trying to get the user name by id and pass it to view by viewbag.
I can access the user by id but I can't access the user name.
I'm using identity 3 in asp.net core.
This is my action:
public IActionResult Index(string id)
{
var userCourse = _courseService.GetUserCourse(id);
var user = _userManager.FindByIdAsync(id);
return View(userCourse);
}
public async Task<IActionResult> Index(string id)
{
var userCourse = _courseService.GetUserCourse(id);
var user = await _userManager.FindByIdAsync(id);
ViewBag.UserName= user.UserName;
return View(userCourse);
}
And in View use viewbag.UserName to render userName
<label>User Name:</label> #ViewBag.UserName
Related
I'm trying to get the current user ID so my Events index page will show events from only current user.
my HttpContext.User has the error "Cannot convert from System.security.claims.claimsPrincipal to Scheduler.Areas.Identity.Data" inside the index of my Events controller.
var userId = await _userManager.GetUserIdAsync(HttpContext.User);
Here is the code in my EventsController:
public EventsController(SchedulerDbContext context, UserManager<SchedulerUser> userManager)
{
_context = context;
_userManager = userManager;
}
// GET: Events
[Authorize]
public async Task<IActionResult> Index()
{
var userId = await _userManager.GetUserIdAsync(HttpContext.User);
return View(await _context.Events.Where(g => g.SchedulerUser == userId).ToListAsync());
}
Where should I be looking to solve this? I'll update with more code if required.
GetUserIdAsync only accepts an IdentityUser type. It doesn't accept a type of ClaimsPrincipal, but GetUserAsync does.
var user = await _userManager.GetUserAsync(HttpContext.User);
var userId = user.Id;
Alternatively, you could also get the Id claim from claimsidentity.
var userId = claimsIdentity.FindFirst("id")?.Value;
Greeting,
I have an website that display products everything okay until now but i want the current user that have logged in to get his/ her data only, eg. if the user has id=1 its will get all products will id=1 (i have foreign key constrain between the two tables) i am using very simple controller that only get all products, i didn't find any solution at google.
i am using .NET CORE 3.0 with EntityFramework and SQL SERVER database
i am currently using JWT token that is stored inside local storage at web browser.
here is my ProductsController
public class ProductsController : ControllerBase
{
private readonly IAuthRepository _repo;
private readonly DataContext _context;
public ProductsController(DataContext context, IAuthRepository repo)
{
_context = context;
_repo = repo;
}
[HttpGet]
public async Task<IActionResult> AllProducts()
{
var All = await _context.Product.ToListAsync();
return Ok(All);
}
below is the code to get userid from jwt token
var context = new HttpContextAccessor();
var principal = context.HttpContext.User;
if (null == principal)
return null;
var id = principal.FindFirstValue(ClaimTypes.NameIdentifier);
Then update your action method " AllProducts" to
[HttpGet]
public async Task<IActionResult> AllProducts()
{
var context = new HttpContextAccessor();
var principal = context.HttpContext.User;
if (null == principal)
return null;
var userid = principal.FindFirstValue(ClaimTypes.NameIdentifier);
var All = await _context.Product.where(p=>p.id==userid).ToListAsync();
return Ok(All);
}
How can i display data in views in asp.net core MVC?. In the Index.cshtml I have the following link to the detail page.
#Html.ActionLink("You_Controller_Name", "GetProductsDetail", new { id = item.ID }) |
I have this controller to get product by ID
public IActionResult Detail()
{
return View();
}
[HttpGet()]
public async Task<IActionResult> GetProductsDetail(string id)
{
var product_list = (await ProductService.GetProducts()).ToList();
var product = product_list.FirstOrDefault(a => a.ProductCode == id);
return view(product);
}
Need help on displaying Product information in the detail page.
You could also pass the ProductName to Detail action using RedirectToAction,and then display it on view using ViewBag.
Controller:
[HttpGet]
public async Task<IActionResult> GetProductsDetail(string id)
{
var product_list = (await ProductService.GetProducts()).ToList();
var product = product_list.FirstOrDefault(a => a.ProductCode == id);
return RedirectToAction("Detail", new { name = product.ProductName });
}
public IActionResult Detail(string name)
{
ViewBag.ProductName = name;
return View();
}
Detail View:
<h1>#ViewBag.ProductName</h1>
You should do this in GetProductsDetail Action
return View("Detail", product);
Read the following to have a better understanding
Updated
You can store like this in
#ViewBag.ProductName = product.ProductName
In View:
<h1>#ViewBag.ProductName</h1>
Full code
[HttpGet]
public async Task<IActionResult> GetProductsDetail(string id)
{
var product_list = (await ProductService.GetProducts()).ToList();
var product = product_list.FirstOrDefault(a => a.ProductCode == id);
#ViewBag.ProductName = product.ProductName
return View("Detail", product); // Make sure that in View is expecting `ProductList`, Otherwise, You just return View("Detail");
}
Calling another different view from the controller using ASP.NET MVC 4
I am using Open Id Connect with Azure Active Directory for authentication. I am also setting a parameter to the OpenIdConnectChallengeProperties, so that I can retrieve this parameter in the controller action which is the redirect URL.
I did not find any information on how to do this.
My code is as follows.
AuthController.cs
[Route("auth/signin")]
[HttpPost]
public ActionResult SignIn([FromBody] RequestParams requestParams)
{
Guid guid = new Guid();
_cache.Set(guid, requestParams);
var baseURL = Request.Host;
var redirectURL = "https://" + baseURL + "/auth/redirect";
var properties = new OpenIdConnectChallengeProperties();
properties.SetParameter("id",guid);
properties.RedirectUri = redirectURL;
return Challenge(properties, AzureADDefaults.OpenIdScheme);
}
[Route("auth/redirect")]
[HttpGet]
public async Task<string> HandleAADRedirect()
{
if (User.Identity.IsAuthenticated)
{
string accessToken = await HttpContext.GetTokenAsync("access_token");
string idToken = await HttpContext.GetTokenAsync("id_token");
}
return _cache.Get("").ToString();
}
Once the user authenticates and goes back to your server, you can then access the property.
var result = await HttpContext.AuthenticateAsync(OpenIdConnectDefaults.AuthenticationScheme);
var value = result.Properties.Items["id"];
I'm building an history of the action a user called. For this I need all the parameters in the original querystring. This needs to be done in the OnActionExecuted (After the action) because some description information are stored in the filterAction.Result.Model.MyDescription.
On the ActionExecutedContext I do not have access to the ActionParameters and the RoutesValues only contains action, controller, id and culture. It doesn't contains any of the other parameters that was included in the querystring.
How can I preserve the ActionParameters from the OnActionExecuting to the OnActionExecuted?
Controller:
[ReportHistoryLink]
public ActionResult Index(int id, DateTime at, string by)
{
var model = new ReportModel();
model.ReportDescription = "Some logic get the ReportDescription";
return View("Index", model);
}
ActionFilter:
public class ReportHistoryLinkAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var model = (IModelWithReportDescription)((ViewResult)filterContext.Result).Model;
var description = model.ReportDescription;
var boxedId = filterContext.RouteData.Values["id"];
var id = Convert.ToInt32(boxedId);
if (id != 0 && !string.IsNullOrWhiteSpace(targetDescription))
{
var link = new HistoryLink
{
Id = id,
Description = description,
Route = filterContext.RouteData.Values //This doesn't contains the "at and by parameters"
};
}
}
}
You can use
filterContext.HttpContext.Request.QueryString["id"]