using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Services_Website.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
namespace Services_Website.ViewComponents
{
public class CurrentUser : ViewComponent
{
private readonly UserManager<ApplicationUser> _userManager;
private readonly SignInManager<ApplicationUser> _signInManager;
public CurrentUser(UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager)
{
_userManager = userManager;
_signInManager = signInManager;
}
public ApplicationUser Invoke()
{
if (_signInManager.IsSignedIn((ClaimsPrincipal)User))
{
var userId = _userManager.GetUserId((ClaimsPrincipal)User);
var UserFinded = _userManager.FindByIdAsync(userId).Result;
return UserFinded;
}
return null;
}
}
}
这是我的代码,我想在 Invoke 方法中返回 ApplicationUser 或 IdentityUser 的对象,但是当像这样编写代码时,我收到此错误。 我该怎么做
错误
InvalidOperationException:View Components 仅支持返回 String、IHtmlContent 或 IViewComponentResult。
将应用程序用户包装在视图模型中
视图模型
public class CurrentUserVM
{
public ApplicationUser ApplicationUser {get; set;}
}
视图组件代码
public IViewComponentResult Invoke()
{
ApplicationUser user = null;
if (_signInManager.IsSignedIn((ClaimsPrincipal)User))
{
var userId = _userManager.GetUserId((ClaimsPrincipal)User);
user = _userManager.FindByIdAsync(userId).Result;
}
return new CurrentUserVM()
{
ApplicationUser = user;
}
}
视图组件视图
@model CurrentUserVM
// your view code