这是我的控制器动作方法-------
public HttpResponseMessage PostPost(Post post)
{
// previosly i was using simple membership to get id of logged in user
// post.PostedBy = WebSecurity.CurrentUserId;
post.PostedBy = User.Identity.GetUserId<int>();
post.PostedDate = DateTime.UtcNow;
ModelState.Remove("post.PostedBy");
ModelState.Remove("post.PostedDate");
if (ModelState.IsValid)
{
db.Posts.Add(post);
db.SaveChanges();
// now i am facing problem at this line. it is saying that
//Operator '==' cannot be applied to operands of type 'int' and 'string'
var usr = db.Users.FirstOrDefault(x => x.Id == post.PostedBy);
当我使用简单的会员资格时,我的代码工作正常。我应该尝试使其工作。这里,post是一个具有属性PostedBy为int的类,我想将当前的loggedIn userId值赋给此属性。
答案 0 :(得分:0)
检查此链接中的答案:How to get current user, and how to use User class in MVC5?
检查答案中代码的编写方式:
using Microsoft.AspNet.Identity;
...
User.Identity.GetUserId();
如果这不起作用,请调试并跟踪代码并告诉我们User.Identity的价值是什么?