我创建了一个自定义处理程序,如下所示:
public class SitHandler : DelegatingHandler
{
protected override async Task<HttpResponseMessage> SendAsync(
HttpRequestMessage request, CancellationToken cancellationToken)
{
Debug.WriteLine("Process request");
// Call the inner handler.
var response = await base.SendAsync(request, cancellationToken);
Debug.WriteLine("Process response");
return response;
}
}
并在班级中注册WebApiConfig
:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
//Delegating Handlers
config.MessageHandlers.Add(new SitHandler());
// Web API routes
config.MapHttpAttributeRoutes();
/*config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);*/
}
}
并有以下路线:
[RoutePrefix("")]
public class SignInController : Controller
{
[Route("", Name = "Default")]
public ActionResult Index()
{
return View();
}
}
Now when I start the server it show me the correct page as expected:
但请求并没有经过处理程序,为什么?
什么是内部处理程序?
// Call the inner handler.
var response = await base.SendAsync(request, cancellationToken);
对于 MVC,您需要添加一个ActionFilterAttribute
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
public class MyCustomFilter : System.Web.Mvc.ActionFilterAttribute {
public override void OnActionExecuted(ActionExecutedContext context) {
Debug.WriteLine("Process response");
//From here you have access to the response to process what you need
//eg: context.HttpContext.Response.Headers.Add("MyCustomHeaderName","value");
base.OnActionExecuted(context);
}
}
然后您可以在操作上使用您的属性...
[MyCustomFilter]
[Route("", Name = "Default")]
public ActionResult Index(){...}
, 班级...
[MyCustomFilter]
[RoutePrefix("")]
public class SignInController : Controller {...}
,或全局设置...
public class FilterConfig {
public static void RegisterGlobalFilters(GlobalFilterCollection filters) {
filters.Add(new MyCustomFilter());
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)