回答編集履歴

1

追記

2017/05/24 08:24

投稿

退会済みユーザー
test CHANGED
@@ -79,3 +79,109 @@
79
79
  }
80
80
 
81
81
  ```
82
+
83
+
84
+
85
+ *** 2017/5/24 17:23 追記 ***
86
+
87
+
88
+
89
+ 私の 2017/05/24 17:06 のコメントで、「View に渡すならアクションフィルターで OnActionExecuting のタイミングで ViewData にその時点での日時を格納して渡すことができるはずです。検証してから回答欄に書いておきます」と書きました。
90
+
91
+
92
+
93
+ すでに解決したとのことですが、コメントに書いた通り当方でも検証してみましたので、検証に使ったコードをご参考までに以下にアップしておきます。
94
+
95
+
96
+
97
+ 上に書いたコードでは OnResultExecuted のタイミングで処理してますが、その時点で ViewData に追加しても遅すぎで View では取得できないので、OnActionExecuting のタイミングに変えました。
98
+
99
+
100
+
101
+ ```
102
+
103
+ using System;
104
+
105
+ using System.Collections.Generic;
106
+
107
+ using System.Linq;
108
+
109
+ using System.Web;
110
+
111
+ using System.Web.Mvc;
112
+
113
+ using Mvc5App.Models;
114
+
115
+
116
+
117
+ namespace Mvc5App.Extensions
118
+
119
+ {
120
+
121
+ public class AccessLogAttribute : ActionFilterAttribute
122
+
123
+ {
124
+
125
+ public override void OnActionExecuting(ActionExecutingContext filterContext)
126
+
127
+ {
128
+
129
+ if (filterContext == null)
130
+
131
+ {
132
+
133
+ throw new ArgumentNullException("ActionExecutingContext が null");
134
+
135
+ }
136
+
137
+
138
+
139
+ HttpContextBase context = filterContext.HttpContext;
140
+
141
+
142
+
143
+ if (context.User.Identity.IsAuthenticated)
144
+
145
+ {
146
+
147
+ using (var db = new ApplicationDbContext())
148
+
149
+ {
150
+
151
+ // User.Identity.Name はデフォルトで email と同じになりかつユニーク
152
+
153
+ string userName = context.User.Identity.Name;
154
+
155
+ ApplicationUser user = db.Users.FirstOrDefault(u => u.UserName == userName);
156
+
157
+ // アクセス日時の DB への登録
158
+
159
+
160
+
161
+ // ViewData に最新アクセス日時を設定
162
+
163
+ ViewDataDictionary dic = filterContext.Controller.ViewData;
164
+
165
+ dic["LastAccessDateTime"] = DateTime.Now.ToString();
166
+
167
+ }
168
+
169
+ }
170
+
171
+
172
+
173
+ base.OnActionExecuting(filterContext);
174
+
175
+ }
176
+
177
+ }
178
+
179
+ }
180
+
181
+ ```
182
+
183
+
184
+
185
+ View 側では @ViewData["LastAccessDateTime"] で取得できます。
186
+
187
+