2

私がやっていることは単純に思えるかもしれませんが、正確な方法はわかりません。

私はすでにアカウントを登録してログインしています (ASP.NET MVC 4 で使用されている既定のメンバーシップ システムを使用しています)。そのため、データベースに挿入するデータに UserId を追加したいと考えています。

これは、挿入するデータのモデルです。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Reroute.Models
{
    public class Request
    {
        public int      RequestId { get; set; }
        // I want to add UserId based on my current session
        public int      UserId { get; set; }
        public string   OrderNumber { get; set; }
        public string   TrackingNumber { get; set; }
        public string   CurrentAddress { get; set; }
        public string   NewAddress { get; set; }
        public string   Comment { get; set; }
    }
}

そしてActionResult(ここで私は変更を加える必要があると思いました):

[HttpPost]
public ActionResult Create(Request collection)
{
    try
    {
        _db.Requests.Add(collection);
        _db.SaveChanges();
        //return RedirectToAction("Index");
        return Content("Done! Added to DB");
     }
     catch
     {
        return View();
     }
 }

ありがとう

4

4 に答える 4

0

これはうまくいくはずです。

var loggedInUserName=Thread.CurrentPrincipal.Identity.Name;
var user=Membership.GetUser(loggedInUserName);
var key = user.ProviderUserKey;

T

于 2013-04-03T01:55:18.343 に答える
0

ログイン後、認証されたユーザーの UserId を Session に保存できます。

Session["UserId"] = userId;

または、FormsAuthentication を使用しているため、ここに示すように UserData プロパティを使用するか、適切なトリックを実行できます。

public SignInUser(string name, string id) {
    // store the userid
    FormsAuthentication.SetAuthCookie(name + '|' + id, false);
}

次に、次のように Name と UserId を取得します。

public int CurrentUserId
{
    get
    {
        var context = HttpContext.Current;
        if (context == null) return 0;

        return context.Request.IsAuthenticated
                    ? Convert.ToInt32(context.User.Identity.Name.Split('|')[1])
                    : 0;
    }
}

public string CurrentUserName
{
    get
    {
        var context = HttpContext.Current;
        if (context == null) return string.Empty;

        return context.Request.IsAuthenticated 
            ? context.User.Identity.Name.Split('|')[0] 
            : string.Empty;
    }
}

これらのメソッドとプロパティをクラスに含めることができるので、それらを 1 か所にまとめることができます。私は実際にそのようにしています。これで、コントローラーで次のように呼び出すことができます。

[HttpPost]
public ActionResult Create(Request collection)
{
    try
    {
        collection.UserId = _authProvider.CurrentUserId;
        // if you want to use session, I prefer the FormsAuthentication approach
        // you need to do additional check that the Session has not expired (not null)
        collection.UserId = Session["UserId"];

        _db.Requests.Add(collection);
        _db.SaveChanges();
        //return RedirectToAction("Index");
        return Content("Done! Added to DB");
    }
    catch
    {
        return View();
    }
}

_authProvider上記のコードを持つクラスのインスタンスです。

于 2013-04-03T00:47:46.490 に答える
0

これを使用すると、ユーザーIDが取得されます...

Membership.GetUser().ProviderUserKey
于 2013-04-03T09:57:46.277 に答える
0

ロードされて のモデルとして使用されるCreateもあると仮定すると、その中で明示的に設定する必要があります。GETCreate.cshtmlActionResult

public ActionResult Create() 
{
   Result model = new Result();
   model.UserId = myUserId;
}

次に、あなたCreate.cshtmlの隠しフィールドを持つことができます:

@Html.HiddenFor(m => m.UserId)

私はまだチェックインしPOSTて、保存を行っているユーザーが保存を許可されており、隠しフィールドの値をまったく別の誰かに偽装していないことを確認します。

于 2013-04-03T02:09:38.990 に答える