如何在Asp.Net-MVC中添加自定义HTTP标头 [英] How to add custom HTTP Headers in Asp.Net-MVC
本文介绍了如何在Asp.Net-MVC中添加自定义HTTP标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建了一个自定义处理程序,如下所示:
I created a custom handler that looks like follow:
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:
但是请求没有通过处理程序,为什么?
什么是内部处理程序?
But the request does not goi throught the handler, why?
And what is an innerhandler?
// Call the inner handler.
var response = await base.SendAsync(request, cancellationToken);
推荐答案
对于MVC,您需要添加ActionFilterAttribute
For MVC you will need to add an 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);
}
}
然后您可以在操作上使用您的属性...
you can then either use you attribute on an action...
[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());
}
}
这篇关于如何在Asp.Net-MVC中添加自定义HTTP标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文