java 得到登陆用户的id_如何在ASP.NET Core中获取当前登录的用户ID

User.Identity.GetUserId();

asp.net identity core 2.0中不存在 . 在这方面,我以不同的方式管理 . 我已经创建了一个用于整个应用程序的公共类,因为它获取了用户信息 .

create a common class PCommon & interface IPCommon 正在添加参考 using System.Security.Claims

using Microsoft.AspNetCore.Http;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Security.Claims;

using System.Threading.Tasks;

namespace Common.Web.Helper

{

public class PCommon: IPCommon

{

private readonly IHttpContextAccessor _context;

public PayraCommon(IHttpContextAccessor context)

{

_context = context;

}

public int GetUserId()

{

return Convert.ToInt16(_context.HttpContext.User.FindFirstValue(ClaimTypes.NameIdentifier));

}

public string GetUserName()

{

return _context.HttpContext.User.Identity.Name;

}

}

public interface IPCommon

{

int GetUserId();

string GetUserName();

}

}

这里执行常见的类

using Microsoft.AspNetCore.Authorization;

using Microsoft.AspNetCore.Mvc;

using Microsoft.AspNetCore.Mvc.Rendering;

using Microsoft.Extensions.Logging;

using Pay.DataManager.Concreate;

using Pay.DataManager.Helper;

using Pay.DataManager.Models;

using Pay.Web.Helper;

using Pay.Web.Models.GeneralViewModels;

using System;

using System.Collections.Generic;

using System.Linq;

using System.Threading.Tasks;

namespace Pay.Controllers

{

[Authorize]

public class BankController : Controller

{

private readonly IUnitOfWork _unitOfWork;

private readonly ILogger _logger;

private readonly IPCommon _iPCommon;

public BankController(IUnitOfWork unitOfWork, IPCommon IPCommon, ILogger logger = null)

{

_unitOfWork = unitOfWork;

_iPCommon = IPCommon;

if (logger != null) { _logger = logger; }

}

public ActionResult Create()

{

BankViewModel _bank = new BankViewModel();

CountryLoad(_bank);

return View();

}

[HttpPost, ActionName("Create")]

[ValidateAntiForgeryToken]

public async Task Insert(BankViewModel bankVM)

{

if (!ModelState.IsValid)

{

CountryLoad(bankVM);

//TempData["show-message"] = Notification.Show(CommonMessage.RequiredFieldError("bank"), "Warning", type: ToastType.Warning);

return View(bankVM);

}

try

{

bankVM.EntryBy = _iPCommon.GetUserId();

var userName = _iPCommon.GetUserName()();

//_unitOfWork.BankRepo.Add(ModelAdapter.ModelMap(new Bank(), bankVM));

//_unitOfWork.Save();

// TempData["show-message"] = Notification.Show(CommonMessage.SaveMessage(), "Success", type: ToastType.Success);

}

catch (Exception ex)

{

// TempData["show-message"] = Notification.Show(CommonMessage.SaveErrorMessage("bank"), "Error", type: ToastType.Error);

}

return RedirectToAction(nameof(Index));

}

}

}

在插入操作中获取userId和name

_iPCommon.GetUserId();

谢谢,马克苏德

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值