Can I simplify this code for reverse lookups? It seems very redundant

Is there a way to compress them into only one group result? I have a set of pages that simply return static content and think there should be a more efficient way to do this.

public ActionResult Research() { return View(); } public ActionResult Facility() { return View(); } public ActionResult Contact() { return View(); } 

EDIT: Thanks for all the answers :)

+6
source share
3 answers

You can create a general action method that accepts the viewName parameter:

 public ActionResult Show(string viewName) { return View(viewName); } 

Then you can redirect these names to this action:

 routes.MapRoute( "Simple Content", "/{viewName}", new { controller = "Something", action = "Show" }, new { viewName = "Research|Facility|Contact" } ); 

A viewName restriction viewName necessary to prevent this route from matching arbitrary URLs.

Beware that this is a disclosure vulnerability; an attacker can request /ControllerName/Show?viewName=~/Views/Secret/View .
If you have any confidential views that do not use models, you must confirm the viewName in action.
You can use an enumeration for this, as in dknaack's answer .

+9
source

You can create a new route that only takes controllername/{path} , and the path will be your view name, and then in the controller, something like this

 public ActionResult Page(string path) { return View(path); } 

So, let's move on to this path.

yourdomain.com/controllername/Ijusttest load the view from ~/Views/controllername/Ijusttest.cshtml . You just have to be sure to name your action from the route.

Hope this makes sense. You can configure it differently, it all depends on the routing you create. Let me know if you need help with a route code.

+2
source

You might want to create one action and pass an argument as the page name, for example

 public StaticContent : Controller { public ActionResult Pages(string id) { return View(id); } } 

Where the id may have the meanings of Investigation, Object, etc.

You will get a URL like these / staticcontent / pages / research

Just specify the views in the StaticContent Research.cshtml folder, for example.

0
source

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


All Articles