ASP.NET MVC 4는 들어오는 모든 요청을 가로 챕니다.
ASP.NET MVC 4 앱으로 들어오는 모든 요청 을 포착 하고 지정된 컨트롤러 / 작업에 대한 요청을 계속하기 전에 일부 코드를 실행할 수있는 방법이 있습니까?
기존 서비스에서 일부 사용자 지정 인증 코드를 실행해야하며이 작업을 제대로 수행하려면 모든 클라이언트에서 들어오는 모든 요청을 가로 채서 다른 서비스에서 몇 가지 사항을 다시 확인할 수 있어야합니다.
가장 올바른 방법은 ActionFilterAttribute 를 상속 하고 OnActionExecuting
메서드를 재정의 하는 클래스를 만드는 것 입니다. 그런 다음에 등록 할 수 있습니다 GlobalFilters
.Global.asax.cs
물론 이것은 실제로 경로가있는 요청 만 가로 챌 것입니다.
HttpModule을 사용하여이를 수행 할 수 있습니다. 다음은 모든 요청의 처리 시간을 계산하는 데 사용하는 샘플입니다.
using System;
using System.Diagnostics;
using System.Web;
namespace Sample.HttpModules
{
public class PerformanceMonitorModule : IHttpModule
{
public void Init(HttpApplication httpApp)
{
httpApp.BeginRequest += OnBeginRequest;
httpApp.EndRequest += OnEndRequest;
httpApp.PreSendRequestHeaders += OnHeaderSent;
}
public void OnHeaderSent(object sender, EventArgs e)
{
var httpApp = (HttpApplication)sender;
httpApp.Context.Items["HeadersSent"] = true;
}
// Record the time of the begin request event.
public void OnBeginRequest(Object sender, EventArgs e)
{
var httpApp = (HttpApplication)sender;
if (httpApp.Request.Path.StartsWith("/media/")) return;
var timer = new Stopwatch();
httpApp.Context.Items["Timer"] = timer;
httpApp.Context.Items["HeadersSent"] = false;
timer.Start();
}
public void OnEndRequest(Object sender, EventArgs e)
{
var httpApp = (HttpApplication)sender;
if (httpApp.Request.Path.StartsWith("/media/")) return;
var timer = (Stopwatch)httpApp.Context.Items["Timer"];
if (timer != null)
{
timer.Stop();
if (!(bool)httpApp.Context.Items["HeadersSent"])
{
httpApp.Context.Response.AppendHeader("ProcessTime",
((double)timer.ElapsedTicks / Stopwatch.Frequency) * 1000 +
" ms.");
}
}
httpApp.Context.Items.Remove("Timer");
httpApp.Context.Items.Remove("HeadersSent");
}
public void Dispose() { /* Not needed */ }
}
}
And this is how you register the module in Web.Config:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<add name="PerformanceMonitorModule" type="Sample.HttpModules.PerformanceMonitorModule" />
</modules>
<//system.webServer>
I think that what you search for is this:
Application_BeginRequest()
http://www.dotnetcurry.com/showarticle.aspx?ID=126
You put it in Global.asax.cs
.
protected void Application_BeginRequest(object sender, EventArgs e)
{
HttpContext.Current.Request.....;
}
I use this for debugging purposes but I am not sure how good solution it is for your case.
I'm not sure about MVC4 but I think it is fairly similar to MVC5. If you have created a new web project -> look in Global.asax
and you should see the following line FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
in the method Application_Start()
.
RegisterGlobalFilters
is a method in the file FilterConfig.cs
located in the folder App_Start
.
As @YngveB-Nilsen said ActionFilterAttribute
is the way to go in my opinion. Add a new class that derives from System.Web.Mvc.ActionFilterAttribute
. This is important because System.Web.Http.Filters.ActionFilterAttribute
will fail with the following exception for example.
The given filter instance must implement one or more of the following filter interfaces: System.Web.Mvc.IAuthorizationFilter, System.Web.Mvc.IActionFilter, System.Web.Mvc.IResultFilter, System.Web.Mvc.IExceptionFilter, System.Web.Mvc.Filters.IAuthenticationFilter.
Example that writes the request to the debug window:
public class DebugActionFilter : System.Web.Mvc.ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
Debug.WriteLine(actionContext.RequestContext.HttpContext.Request);
}
}
In FilterConfig
-> RegisterGlobalFilters
-> add the following line: filters.Add(new DebugActionFilter());
.
You can now catch all incoming requests and modify them.
참고URL : https://stackoverflow.com/questions/11726848/asp-net-mvc-4-intercept-all-incoming-requests
'IT박스' 카테고리의 다른 글
플래시 기반 웹 사이트가 왜 그렇게 나쁜가요? (0) | 2020.10.20 |
---|---|
Console.WriteLine을 사용하여 열의 텍스트를 어떻게 정렬 할 수 있습니까? (0) | 2020.10.20 |
CSS와 함께 FontAwesome 또는 Glyphicons 사용 : before (0) | 2020.10.19 |
MySQL에서 가장 가까운 정수로 내림하는 방법은 무엇입니까? (0) | 2020.10.19 |
매개 변수 개체에서 쿼리 문자열 작성 (0) | 2020.10.19 |