基于 Http Header 值的 ASP.NET MVC5/6 路由 [英] ASP.NET MVC5/6 Routing based on Http Header values
问题描述
假设我有一个最基本的控制器
Let's say I have a most basic controller
public class HomeController : Controller
{
public ActionResult Index(string id, string language)
{
return View();
}
}
它接受 2 个参数.然而,有一个要求是调用 action 方法的客户端应该从 URL 传递 id
值,但从 http 标头传递 language
值.这意味着url应该是/Home/Index/12345
,同时调用客户端将设置一个Http Header值language : en
.
Which takes in 2 parameters. However there is one requirement that the client which calls the action method should pass id
value from URL but language
value from http header. It means the url should be /Home/Index/12345
and meanwhile the calling client will set a Http Header value language : en
.
如何在MVC5或MVC6中设置路由来达到要求?
How shall I set the routing in MVC5 or MVC6 to achieve the requirement?
请不要提供来自 Web Api 的示例.
Please don't provide samples from Web Api.
谢谢
推荐答案
有一个属性 FromHeaderAttribute
.来自其文档:
There is an attribute FromHeaderAttribute
. From its documentation:
指定一个参数或属性应该使用请求标头.
Specifies that a parameter or property should be bound using the request headers.
您应该能够将其添加到控制器的语言参数中.默认情况下,它会查找与参数同名的标头,但它也有一个 name
参数可用于指定不同的名称,例如:
You should be able to add it to the language parameter of your controller. By default it will look for a header with the same name than the parameter, but it also has a name
parameter that can be used to specify a different name, for example:
public ActionResult Index(string id, [FromHeader(Name="Accept-Language")]string language)
{
return View();
}
您还可以查看位于 github MVC 存储库.检查名为 FromHeader_BlogController
的控制器.
You can also have a look to the test site ModelBindingWebSite located in the github MVC repo. Check the controller named FromHeader_BlogController
.
PS 查看HeaderModelBinder
看来这可以用于绑定字符串和数组(假设标题有一个逗号分隔的值列表)
PS Looking at the source code of the HeaderModelBinder
it seems this can be used for binding strings and arrays (assuming the header has a comma separated list of values)
这篇关于基于 Http Header 值的 ASP.NET MVC5/6 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!