Skip to content

Instantly share code, notes, and snippets.

@Implem
Last active August 29, 2015 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Implem/0dcaecc5f2b11e89c95c to your computer and use it in GitHub Desktop.
Save Implem/0dcaecc5f2b11e89c95c to your computer and use it in GitHub Desktop.
c# ASP.NET MVCで引数を渡さずに呼び出し元コントローラー名、アクション名をセットする ref: http://qiita.com/Implem/items/badc102c98e8580f73b9
using System.Collections.Specialized;
using System.Diagnostics;
using System.Linq;
using System.Web;
namespace Implem.Sample
{
public class Logger
{
public HttpContext HttpContext;
public NameValueCollection Form { get { return HttpContext.Request.Form; } }
// 呼び出し元コントローラー名(クラス名)
public string ClassName;
// 呼び出し元アクション名(メソッド名)
public string MethodName;
// 引数無しで初期化
public Logger()
{
if (HttpContext.Current != null && HttpContext.Current.Session != null)
{
HttpContext = HttpContext.Current;
// Controller以外(Global.asax等)からアクセスされた場合
// コンテキストからコントローラー名、アクション名をセット
SetCallerDataByContext();
}
else
{
// Controller以外(Global.asax等)からアクセスされた場合
// スタックフレームからクラス名、メソッド名をセット
SetCallerDataByStackFrame();
}
}
private void SetCallerDataByContext()
{
// コンテキスト内のルートデータから取得
var routeData = System.Web.Routing.RouteTable.Routes
.GetRouteData(new System.Web.HttpContextWrapper(HttpContext));
ClassName = routeData.Values["controller"].ToString();
MethodName = routeData.Values["action"].ToString();
}
private void SetCallerDataByStackFrame()
{
// コンストラクタ .ctor を除く最新のスタックフレームから取得
var method = new StackTrace(1, false).GetFrames()
.Select(o => o.GetMethod()).Where(o => o.Name != ".ctor").First();
ClassName = method.ReflectedType.Name;
MethodName = method.Name;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment