回答編集履歴
1
追記
answer
CHANGED
@@ -38,4 +38,56 @@
|
|
38
38
|
}
|
39
39
|
}
|
40
40
|
}
|
41
|
-
```
|
41
|
+
```
|
42
|
+
|
43
|
+
*** 2017/5/24 17:23 追記 ***
|
44
|
+
|
45
|
+
私の 2017/05/24 17:06 のコメントで、「View に渡すならアクションフィルターで OnActionExecuting のタイミングで ViewData にその時点での日時を格納して渡すことができるはずです。検証してから回答欄に書いておきます」と書きました。
|
46
|
+
|
47
|
+
すでに解決したとのことですが、コメントに書いた通り当方でも検証してみましたので、検証に使ったコードをご参考までに以下にアップしておきます。
|
48
|
+
|
49
|
+
上に書いたコードでは OnResultExecuted のタイミングで処理してますが、その時点で ViewData に追加しても遅すぎで View では取得できないので、OnActionExecuting のタイミングに変えました。
|
50
|
+
|
51
|
+
```
|
52
|
+
using System;
|
53
|
+
using System.Collections.Generic;
|
54
|
+
using System.Linq;
|
55
|
+
using System.Web;
|
56
|
+
using System.Web.Mvc;
|
57
|
+
using Mvc5App.Models;
|
58
|
+
|
59
|
+
namespace Mvc5App.Extensions
|
60
|
+
{
|
61
|
+
public class AccessLogAttribute : ActionFilterAttribute
|
62
|
+
{
|
63
|
+
public override void OnActionExecuting(ActionExecutingContext filterContext)
|
64
|
+
{
|
65
|
+
if (filterContext == null)
|
66
|
+
{
|
67
|
+
throw new ArgumentNullException("ActionExecutingContext が null");
|
68
|
+
}
|
69
|
+
|
70
|
+
HttpContextBase context = filterContext.HttpContext;
|
71
|
+
|
72
|
+
if (context.User.Identity.IsAuthenticated)
|
73
|
+
{
|
74
|
+
using (var db = new ApplicationDbContext())
|
75
|
+
{
|
76
|
+
// User.Identity.Name はデフォルトで email と同じになりかつユニーク
|
77
|
+
string userName = context.User.Identity.Name;
|
78
|
+
ApplicationUser user = db.Users.FirstOrDefault(u => u.UserName == userName);
|
79
|
+
// アクセス日時の DB への登録
|
80
|
+
|
81
|
+
// ViewData に最新アクセス日時を設定
|
82
|
+
ViewDataDictionary dic = filterContext.Controller.ViewData;
|
83
|
+
dic["LastAccessDateTime"] = DateTime.Now.ToString();
|
84
|
+
}
|
85
|
+
}
|
86
|
+
|
87
|
+
base.OnActionExecuting(filterContext);
|
88
|
+
}
|
89
|
+
}
|
90
|
+
}
|
91
|
+
```
|
92
|
+
|
93
|
+
View 側では @ViewData["LastAccessDateTime"] で取得できます。
|