ASP.NET MVC5/6 Routing based on Http Header values

岁酱吖の 提交于 2019-11-29 14:45:11

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

You can also have a look to the test site ModelBindingWebSite located in the github MVC repo. Check the controller named FromHeader_BlogController.

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)

jltrem

As Daniel J.G. said, you can bind a Controller action parameter with FromHeaderAttribute. But keep in mind that a Controller can access Request.Headers directly. It might be nicer to leave off the Controller's language parameter and access the value as an enumeration via a property:

  public enum LanguageType
  {
     Unknown = -1,
     English,
     Spanish,
     German,
     Chinese
  }

  public LanguageType Language
  {
     get
     {
        string langStr = Request.Headers["Accept-Language"];
        switch (langStr.ToLower())
        {
           case "english":
              return LanguageType.English;
           case "spanish":
              return LanguageType.Spanish;
           case "german":
              return LanguageType.German;
           case "chinese":
              return LanguageType.Chinese;
           default:
              return LanguageType.Unknown;
        }
     }
  }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!