Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
459 views
in Technique[技术] by (71.8m points)

c# - 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();
    }
}

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.

How shall I set the routing in MVC5 or MVC6 to achieve the requirement?

Please don't provide samples from Web Api.

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...