The best way to differentiate MVC controllers based on HTTP headers

Problem

In my current project, I need to do different things based on different HTTP request headers for almost every action.

I currently have one massive controller (all for the same resource type), and each action method has an ActionName attribute (so that I can have multiple versions of the same action that take the same parameters, but doing different things) and a custom FilterAttribute attribute (implemented in much the same way as AcceptVerbsAttribute in Preview 5), which checks if certain headers have certain values.

I would really like to direct the code to individual controllers and choose a RouteTable between them based on the headers, but I can’t come up with the cleanest way to do this.

Example

For example, let's say I have a list of files. The service must process the request in one of two ways:

  • The client wants a zip file and passes "accept: application / zip" as the header, I take the list of files, pack them into a zip file and send them back to the client.

  • The client wants an html page, so he sends "accept: text / html", the site sends back the html page in the format of a table in which the files are listed.

+3
source share
4 answers

, , , . .

, , , , ActionResult, Http.

, , (IRoutConstraint), . HttpMethodConstraint .

+4

, ; . , , , , , , , ?

0

, , , AcceptVerbs, Preview 5. , ( MVC), , - .

0

. json xml http.

0

Source: https://habr.com/ru/post/1697009/


All Articles