如何使用User.Identity.GetUserId()以使模型状态有效?

时间:2016-04-07 04:20:27

标签: asp.net-mvc-5 asp.net-identity modelstate

我希望跟踪整个应用程序中发生的每笔交易,因为我正在使用"保存登录用户的用户ID。 User.Identity.GetUserId(); "但我无法在视图上分配用户ID,因此它将被公开。试图从控制器中保存该ID

域模型

public class DemoForIdentity
{
    [Key]
    public string Id { get; set; }
    public string  Address { get; set; }
}

控制器

[HttpPost]
[ValidateAntiForgeryToken]
// public ActionResult Create([Bind(Include = "Id,Address")] DemoForIdentity demoForIdentity)
public ActionResult Create([Bind(Include = "Address")] DemoForIdentity demoForIdentity)
{
    demoForIdentity.Id = User.Identity.GetUserId();
    // Model state will be invalid here. 
    //I can't access User.Identity.GetUserId() from viewmodel and set the value for hidden feild 
    if (ModelState.IsValid)
    {
        db.DemoForidenitity.Add(demoForIdentity);
        db.SaveChanges();
        return RedirectToAction("Index");
    }
    return View(demoForIdentity);
}

查看

@model Try.Models.DemoForIdentity
....
@using (Html.BeginForm()) 
{
    @Html.AntiForgeryToken()  
    <div class="form-horizontal">
        <h4>DemoForIdentity</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        // <div class="form-group">
            // @Html.LabelFor(model => model.Id, htmlAttributes: new { @class = "control-label col-md-2" })
            // <div class="col-md-10">
                // @Html.EditorFor(model => model.Id, new { htmlAttributes = new { @class = "form-control" } })
                // @Html.ValidationMessageFor(model => model.Id, "", new { @class = "text-danger" })
            // </div>
        // </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Address, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Address, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Address, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

我在视图中评论过id。

每次保存用户ID最安全的方法是什么?

0 个答案:

没有答案