基于HTTP标头值ASP.NET MVC5 / 6路由 [英] ASP.NET MVC5/6 Routing based on Http Header values

查看:206
本文介绍了基于HTTP标头值ASP.NET MVC5 / 6路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

让我们说我有一个最基本的控制器。

Let's say I have a most basic controller

public class HomeController : Controller
{
    public ActionResult Index(string id, string language)
    {
        return View();
    }
}

其中发生在2参数。但是有一个要求,即它调用的操作方法应该从http通 ID 从URL值,但语言价值客户端头。这意味着该URL应 /首页/索引/ 12345 ,同时调用客户端将设置一个HTTP标头值语言:zh

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?

请不要从网页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.

您应该可以将其添加到您的控制器的语言参数。默认情况下它会寻找比参数相同名称的头,但它也有一个名称参数可用于指定一个不同的名称,例如:

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="Accepted-Language")]string language)
{
    return View();
}

您还可以看看到测试现场的 ModelBindingWebSite 位于<一个href=\"https://github.com/aspnet/Mvc/blob/e0b8532735997c439e11fff68dd342d5af59f05f/test/WebSites/ModelBindingWebSite/Controllers/FromHeader_BlogController.cs\"相对=nofollow> 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 看的<一个源$ C ​​$ C href=\"https://github.com/aspnet/Mvc/blob/dev/src/Microsoft.AspNet.Mvc.Core/ModelBinding/HeaderModelBinder.cs\"相对=nofollow> 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标头值ASP.NET MVC5 / 6路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆