Showing posts with label routing. Show all posts
Showing posts with label routing. Show all posts

Friday, July 20, 2018

Registering Actions for ControllerModel in ASP.NET Core

Leave a Comment

I am trying to add a new ActionModel for a ControllerModel in an implementation of IControllerModelConvention, but I cannot find any documentation or examples of how this model system works or how to do this correctly. I am able to add a new ActionModel easily enough, but it is not routable once the application is running:

var action = new ActionModel(method, new object[] { new HttpGetAttribute("/test") }) {     Controller = controller,     ActionName = "test" }; controller.Actions.Add(action); 

It seems I need to add a selector to the action, perhaps other properties as well, but I haven't been able to find one that exposes this action. Also unsure if my attributes are correct/redundant. Ultimately I would like to add multiple actions that do not map 1:1 to the methods in the controller.

1 Answers

Answers 1

I've made it work similiar to your approach. Maybe this can help you:

Controller

public class TestController : Controller {     public IActionResult Index()     {         return Ok(new string[] { "Hello", "World" });     } } 

Model Convention

public class TestControllerModelConvention : IControllerModelConvention {     public void Apply(ControllerModel controller)     {         Type controllerType = typeof(TestController);         MethodInfo indexAction = controllerType.GetMethod("Index");          var testAction = new ActionModel(indexAction, new[] { new HttpGetAttribute("/test") })         {             ActionName = "Index",             Controller = controller         };         controller.Actions.Add(testAction);     } } 

Startup

public void ConfigureServices(IServiceCollection services) {     // other initialitation stuff      services.AddMvc(options =>     {         options.Conventions.Add(new TestControllerModelConvention());     }).SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } 

Now when I start the application and browse "/test" it will hit the controller action.

Read More

Monday, May 21, 2018

Routing in container not working properly

Leave a Comment

Pinging a system in the internet works:

root@553c9e5ce5ea:/# ping -c 1 8.8.8.8       PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data. 64 bytes from 8.8.8.8: icmp_seq=1 ttl=57 time=9.61 ms  --- 8.8.8.8 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 9.619/9.619/9.619/0.000 ms 

Pinging a system in the internal (corporate) network, does not work:

root@553c9e5ce5ea:/# ping -c 1 10.97.179.110 PING 10.97.179.110 (10.97.179.110) 56(84) bytes of data.  --- 10.97.179.110 ping statistics --- 1 packets transmitted, 0 received, 100% packet loss, time 0ms 

The routing in the container is straightforward:

root@553c9e5ce5ea:/# route -n Kernel IP routing table Destination     Gateway         Genmask         Flags Metric Ref    Use Iface 0.0.0.0         172.17.0.1      0.0.0.0         UG    0      0        0 eth0 172.17.0.0      0.0.0.0         255.255.0.0     U     0      0        0 eth0 

Pinging the same system from the docker host is working fine:

host » ping -c 1 10.97.179.110   PING 10.97.179.110 (10.97.179.110) 56(84) bytes of data. 64 bytes from 10.97.179.110: icmp_seq=1 ttl=60 time=4.70 ms  --- 10.97.179.110 ping statistics --- 1 packets transmitted, 1 received, 0% packet loss, time 0ms rtt min/avg/max/mdev = 4.703/4.703/4.703/0.000 ms 

The system is reachable via a vpn interface in the docker host:

host » route -n | grep '^10\.' 10.0.0.0        0.0.0.0         255.248.0.0     U     0      0        0 tunsnx 10.8.0.0        0.0.0.0         255.252.0.0     U     0      0        0 tunsnx 10.12.0.0       0.0.0.0         255.254.0.0     U     0      0        0 tunsnx 10.14.0.0       0.0.0.0         255.255.0.0     U     0      0        0 tunsnx 10.15.0.0       0.0.0.0         255.255.240.0   U     0      0        0 tunsnx 10.15.20.0      0.0.0.0         255.255.252.0   U     0      0        0 tunsnx 10.15.24.0      0.0.0.0         255.255.248.0   U     0      0        0 tunsnx 10.15.32.0      0.0.0.0         255.255.224.0   U     0      0        0 tunsnx 10.15.64.0      0.0.0.0         255.255.192.0   U     0      0        0 tunsnx 10.15.113.108   0.0.0.0         255.255.255.255 UH    0      0        0 tunsnx 10.15.128.0     0.0.0.0         255.255.128.0   U     0      0        0 tunsnx 10.16.0.0       0.0.0.0         255.240.0.0     U     0      0        0 tunsnx 10.32.0.0       0.0.0.0         255.224.0.0     U     0      0        0 tunsnx 10.64.0.0       0.0.0.0         255.192.0.0     U     0      0        0 tunsnx 10.128.0.0      0.0.0.0         255.128.0.0     U     0      0        0 tunsnx 

Why is the host not properly routing the traffic coming from the docker container?

EDIT

I have been checking the IP tables counters, and this is what I see after ping -c 100 (a host on the VPN):

» sudo iptables -x -v --line-numbers -L FORWARD | head Chain FORWARD (policy DROP 0 packets, 0 bytes) num      pkts      bytes target     prot opt in     out     source               destination          1         100     8400 DOCKER-ISOLATION  all  --  any    any     anywhere             anywhere             2           0        0 ACCEPT     all  --  any    docker0  anywhere             anywhere             ctstate RELATED,ESTABLISHED 3           0        0 DOCKER     all  --  any    docker0  anywhere             anywhere             4         100     8400 ACCEPT     all  --  docker0 !docker0  anywhere             anywhere             5           0        0 ACCEPT     all  --  docker0 docker0  anywhere             anywhere             6           0        0 ACCEPT     all  --  any    br-ad32be160e27  anywhere             anywhere             ctstate RELATED,ESTABLISHED 7           0        0 DOCKER     all  --  any    br-ad32be160e27  anywhere             anywhere             8           0        0 ACCEPT     all  --  br-ad32be160e27 !br-ad32be160e27  anywhere             anywhere           

Pinging a host on the internet (8.8.8.8) gives this:

» sudo iptables -x -v --line-numbers -L FORWARD | head Chain FORWARD (policy DROP 0 packets, 0 bytes) num      pkts      bytes target     prot opt in     out     source               destination          1         200    16800 DOCKER-ISOLATION  all  --  any    any     anywhere             anywhere             2         100     8400 ACCEPT     all  --  any    docker0  anywhere             anywhere             ctstate RELATED,ESTABLISHED 3           0        0 DOCKER     all  --  any    docker0  anywhere             anywhere             4         100     8400 ACCEPT     all  --  docker0 !docker0  anywhere             anywhere             5           0        0 ACCEPT     all  --  docker0 docker0  anywhere             anywhere             6           0        0 ACCEPT     all  --  any    br-ad32be160e27  anywhere             anywhere             ctstate RELATED,ESTABLISHED 7           0        0 DOCKER     all  --  any    br-ad32be160e27  anywhere             anywhere             8           0        0 ACCEPT     all  --  br-ad32be160e27 !br-ad32be160e27  anywhere             anywhere      

0 Answers

Read More

Sunday, January 14, 2018

modify back route in laravel

Leave a Comment

In my scenario, I am coming from the following route:

model/{model}/edit 

and I am accessing route:

model/{model}/duplicate 

I make a copy of the model and store it

$duplicate_model = $model->replicate(); $duplicate_model->save(); 

after that I wish to return back to edit route of the new model by doing something along the lines of this:

return redirect()->back()->with('model' => $duplicate_model); 

hoping that it would replace the model id with that of the duplicated model, but it does not.

I cannot access a specific route, because there are different cases in which the duplicate route may be accessed.

2 Answers

Answers 1

One of the solutions is to get resolve to resolve a route name from the back URL like this, provided that all possible back routes are named:

$back_route_name = app('router')->getRoutes()->match(app('request')->create(redirect()->back()->getTargetUrl()))->getName(); 

and then redirect to the route by name:

return redirect()->route($back_route_name, ['template' => $duplicate_template]); 

Answers 2

You can define a "path()" in your model. In this case /

/model/{model}/edit

define a function in your model

public function path() { return '/model/' . $this->id . '/edit'; }

in your ThatModelController.php

simply

return redirect($dumplicate_model->path());

It should work,Jeffery Way uses this convention.

Note: If you are using route model binding and using slug the path() function should return $this->slug instead of $this->id

Read More

Wednesday, August 30, 2017

ExpressJS router normalized/canonical urls

Leave a Comment

I'm after normalized/canonical urls for SPA with ExpressJS server.

Although it is SPA that is backed up by server side router - templates can differ a bit for app urls. One of the differences is <link rel="canonical" href="https://example.com{{ originalPath }}"> tag. Not the relevant detail but explains the context of the question. I expect that there will be only one URL that responds with 200, its variations are redirected to it with 301/302 (works for living humans and search engines).

I would like to make the urls case-sensitive and strict (no extra slash), similarly to Router options, but non-canonical urls (that differ in case or extra slash) should do 301/302 redirect to canonical url instead of 404.

In most apps I just want to force the urls for * routes to be lower-cased (with the exception of queries), with no extra slashes. I.e. app.all('*', ...), and the redirects are:

/Foo/Bar/ -> /foo/bar /foo/Bar?Baz -> /foo/bar?Baz 

But there may be exceptions if the routes are defined explicitly. For example, there are camel-cased routes:

possiblyNestedRouter.route('/somePath')... possiblyNestedRouter.route('/anotherPath/:Param')... 

And all non-canonical urls should be redirected to canonical (parameter case is left intact):

/somepath/ -> /somePath /anotherpath/FOO -> /anotherPath/FOO 

The logic behind canonical urls is quite straightforward, so it is strange that I couldn't find anything on this topic regarding ExpressJS.

What is the best way to do this? Are there middlewares already that can help?

3 Answers

Answers 1

I have looked for npms, I could not find any, so this scratched my mind and I've coded a small task for express to do for each request, which seem to work fine. Please add this to your code.

var urls = {   '/main' : '/main',   '/anotherMain' : '/anotherMain' }  app.use(function(req, res, next){    var index = req.url.lastIndexOf('/');    //We are checking to see if there is an extra slash first   if(req.url[index+1] == null || req.url[index+1] == undefined || req.url[index+1] == '/'){      //slashes are wrong      res.send("please enter a correct url");      res.end();   }else{        for(var item in urls){          if(req.url != item && req.url.toUpperCase() == item.toUpperCase()){            res.redirect(item);            console.log("redirected");            //redirected          }else if (req.url == item) {            console.log("correct url");            next();          }else{            //url doesn't exist          }      }    }   next();  });  app.get('/main', function(req, res){   res.render('mainpage'); });  app.get('/anotherMain', function(req, res){   res.send("here here"); }); 

USAGE

All you have to do is, add your urls to urls object like done above with giving it the same key value. That's it. See how easy it is. Now all of your clients request will be redirected to the correct page case sensitively.

UPDATE

I have also made one for POST requests, I think it is pretty accurate, you should also give it a try. Ff you want a redirect when the user mixes up slashes, you need to write some regex for it. I didn't have time also my brain was fried so I made a simple one. You can change it however you like. Every web structure has its own set of rules.

var urlsPOST = {   '/upload' : '/upload' }  app.use(function(req, res, next){    if(req.method == 'POST'){      var index = req.url.lastIndexOf('/');      if(req.url[index+1] == null || req.url[index+1] == undefined || req.url[index+1] == '/'){         //slashes are wrong        res.sendStatus(400);        res.end();        return false;      }else{        for(var item in urlsPOST){           if(req.url != item && req.url.toUpperCase() == item.toUpperCase()){             res.redirect(307, item);             res.end();             return false;             //redirected            }else if (req.url == item) {             console.log("correct url");             next();            }else{             res.sendStatus(404).send("invalid URL");             return false;             //url doesn't exist           }       }     }   }   next(); }); 

Answers 2

You probably want to write your own middleware for this, something along the lines of this:

app.set('case sensitive routing', true);    /* all existing routes here */    app.use(function(req, res, next) {    var url = find_correct_url(req.url); // special urls only    if(url){      res.redirect(url); // redirect to special url    }else if(req.url.toLowerCase() !=== req.url){      res.redirect(req.url.toLowerCase()); // lets try the lower case version    }else{      next(); // url is not special, and is already lower case    };  });

Now keep in mind this middleware can be placed after all of your current routes, so that if it does not match an existing route you can try to look up what it should be. If you are using case insensitive route matching you would want to do this before your routes.

Answers 3

Using the same code as @user8377060 just with a regex instead.

  // an array of all my urls   var urls = [     '/main',     '/anotherMain'   ]    app.use(function(req, res, next){      var index = req.url.lastIndexOf('/');      //We are checking to see if there is an extra slash first     if(req.url[index+1] == null || req.url[index+1] == undefined || req.url[index+1] == '/'){      //slashes are wrong      res.send("please enter a correct url");      res.end();     }else{        for(var item in urls){          var currentUrl = new RegExp(item, 'i');           if(req.url != item && currentUrl.test(item)){            res.redirect(item);            console.log("redirected");            //redirected          }else if (req.url == item) {            console.log("correct url");            next();          }else{            //url doesn't exist          }      }      }     next();    }); 
Read More

Friday, June 9, 2017

C# MVC Query String Encoding and Decoding

Leave a Comment

I want to encode and decode the url parameters.

calling function in javascript

var url = '/Demo/Demo?id=58'; $(location).attr('href', url) 

Current url parameter

www.example.com/Demo/Demo?id=58

code in Demo controller

public ActionResult Demo(int id) {    return view(); } 

i want the above url to be changed like the bolow line

www.example.com/Demo/Demo?id=Sff5f8ddg

So that the id value will be confidential. what is the best way to encode and decode.

Note: we calling method by anchor tag, ajax and jquery. Encoding and Decoding other than Base64

Is there any cryptography method other than Base64 enoding and decoding like encrypt in javascript and decrypt in C# method

9 Answers

Answers 1

So that the id value will be confidential. what is the best way to encode and decode.

It won't. At least in the way you are trying to make it. As soon as you encode the [internal] id it becomes the public id for that entry. It does not matter for user which id to use: 58 or Sff5f8ddg, as it would refer to the same entry in the system. If you are using unsalted algorithms it would prevent only not so sophisticated users to discover other entries in your system.

As I understand the problem you are trying to solve is - how to make other entries undiscoverable by having an id for some entry(ies). Eg, if user has an url for entry 58, they should not be able to find entries 57 and 59.

The solution is: use GUIDs as ID for your entries.

Also, you need to make sure that you've implemented proper access control for your entries.

Answers 2

var id=Encrypt(YourID); var id=Decrypt(YourID);    using System.Security.Cryptography;  public static string Encrypt(string inputText)     {         string encryptionkey = "SAUW193BX628TD57";         byte[] keybytes = Encoding.ASCII.GetBytes(encryptionkey.Length.ToString());         RijndaelManaged rijndaelCipher = new RijndaelManaged();         byte[] plainText = Encoding.Unicode.GetBytes(inputText);         PasswordDeriveBytes pwdbytes = new PasswordDeriveBytes(encryptionkey, keybytes);         using (ICryptoTransform encryptrans = rijndaelCipher.CreateEncryptor(pwdbytes.GetBytes(32), pwdbytes.GetBytes(16)))         {             using (MemoryStream mstrm = new MemoryStream())             {                 using (CryptoStream cryptstm = new CryptoStream(mstrm, encryptrans, CryptoStreamMode.Write))                 {                 cryptstm.Write(plainText, 0, plainText.Length);                 cryptstm.Close();                 return Convert.ToBase64String(mstrm.ToArray());                 }             }         }     }  public static string Decrypt(string encryptText) {     string encryptionkey = "SAUW193BX628TD57";     byte[] keybytes = Encoding.ASCII.GetBytes(encryptionkey.Length.ToString());     RijndaelManaged rijndaelCipher = new RijndaelManaged();     byte[] encryptedData = Convert.FromBase64String(encryptText.Replace(" ", "+"));     PasswordDeriveBytes pwdbytes = new PasswordDeriveBytes(encryptionkey, keybytes);     using (ICryptoTransform decryptrans = rijndaelCipher.CreateDecryptor(pwdbytes.GetBytes(32), pwdbytes.GetBytes(16)))     {         using (MemoryStream mstrm = new MemoryStream(encryptedData))         {             using (CryptoStream cryptstm = new CryptoStream(mstrm, decryptrans, CryptoStreamMode.Read))             {             byte[] plainText = new byte[encryptedData.Length];             int decryptedCount = cryptstm.Read(plainText, 0, plainText.Length);             return Encoding.Unicode.GetString(plainText, 0, decryptedCount);             }         }     } } 

Answers 3

In javascript, you can use

var str = "Hello World!"; var enc = window.btoa(str); var dec = window.atob(enc); 

The result of res will be:

Encoded String: SGVsbG8gV29ybGQh Decoded String: Hello World! 

This example shows you how to use the RijndaelManaged for encryption decryption.

 public static class Cryptography     {          private static readonly byte[] _key = { 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03, 0x00, 0x01, 0x02, 0x03 };         private static readonly byte[] _iV = { 0x10, 0x11, 0x12, 0x13, 0x10, 0x11, 0x12, 0x13, 0x10, 0x11, 0x12, 0x13, 0x10, 0x11, 0x12, 0x13 };          #region Encryption           public static string Encrypt(this string inputText)         {             string _encryptString = string.Empty;             if (string.IsNullOrEmpty(inputText))                 return string.Empty;             else             {                 ASCIIEncoding textConverter = new ASCIIEncoding();                 RijndaelManaged myRijndael = new RijndaelManaged();                  ICryptoTransform encryptor = myRijndael.CreateEncryptor(_key, _iV);                 MemoryStream msEncrypt = new MemoryStream();                 CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);                 byte[] toEncrypt = textConverter.GetBytes(inputText);                 csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);                 csEncrypt.FlushFinalBlock();                 _encryptString = Convert.ToBase64String(msEncrypt.ToArray()).Replace(" ", "+");                 return _encryptString;             }         }          public static string Decrypt(this string inputText)         {             string text = inputText;             try             {                 if (string.IsNullOrEmpty(inputText))                     return string.Empty;                 else                 {                     inputText = inputText.Replace(" ", "+");                      byte[] encrypted = Convert.FromBase64String(inputText);                     ASCIIEncoding textConverter = new ASCIIEncoding();                     RijndaelManaged myRijndael = new RijndaelManaged();                      ICryptoTransform decryptor = myRijndael.CreateDecryptor(_key, _iV);                     MemoryStream msDecrypt = new MemoryStream(encrypted);                     CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);                     byte[] fromEncrypt = new byte[encrypted.Length];                     csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);                     return textConverter.GetString(fromEncrypt).TrimEnd('\x0');                 }             }             catch (FormatException)             {                 return "";             }             catch (Exception ex)             {                 return text;             }         }            #endregion Encryption      } 

Now encrypt decrypt in controller Like

 "id".Encrypt();///   "encryptID".Decrypt(); 

Answers 4

What I am able to understand from your question is that you want to restrict user from being able to know the exact value of the id parameter.

But that's not gonna help because you already have that value on your browser/client side. so you have id on your client and you want to restrict your client from knowing its value. An average developer(anyone who write code) can access your value using developer tool of browser. So no benefit.

Another way is you send your id encrypted from server itself. For that you can use the solution provided by @Karan Singh. Or any other option you want to explore for that matter is up to you.

One suggestion try to use an encryption method which can not be done in reverse. This will add overhead in processing as you will have to first encrypt your Id from DB and then match it with the value sent by client.

Thanks.

Answers 5

You can simply use jquery function like:

var encodedUrl = encodeURIComponent("your url"); //'/Demo/Demo?id=58'; console.log(encodedUrl);

Thank you

Answers 6

If what you are looking to do is to hide the 58 from the rendered content (client-side), then you need to implement an encryption/decryption scheme on the backend and pass that value from/to the client side as needed.

When you provide data to the client, your server side code will encrypt the 58 into some string in order to conceal the real value and pass that to the client.

When the client issues a request to you, it should use that encrypted string that you provided before and your server should decrypt it into something it can use.

You don't need JavaScript to encrypt and C# to decrypt the values. The JavaScript portion should be working off of the encrypted id at all times since it's scripting that is executing after the fact at the client side. How the value is consumed on the server side is an internal aspect of which the client-side JavaScript does not need to know about.

Answers 7

You want to encode / decode parameters, but the question is why? What are you trying to accomplish in the first place? What is your requirement and how sensitive is the data on the page? What is the purpose of the id, does it identify a user or a page?

If you are thinking of sharing a link or publish it (anchor tag) on an unsecured page, then consider the fact that the link can be shared beyond control or even stolen. Anyone who has the link can access the page. How are you going to detect that it is compromised? How are you going to revoke the link?

It doesn't even matter then how you encrypt the id: a random string, a highly encrypted id, a GUID (which isn't safe either since an attacker will recognize that it's a GUID and can use brute force attack to 'guess' available guid's).

The best chance you may have is to use an auto-expiring link which has some random value and variable length id (so it cannot be guessed). Store the value in the database with expiration date and link to the actual id. This doens't prevent the link from being shared, but at least you can limit possible damage.

But: the only way to prevent unauthorized access is to add a level of security. You can try to think of all kinds of things to secure your data, but in the end you are re-inventing security. Why don't you take a look at modern security, like OpenId Connect and OAuth2. If you want to secure your resource, implement something like Asp.Net Identity 2.

Answers 8

Hello anand i think you want to create a temper proof Query string Download the code from github repository

Answers 9

controller:

[HttpPost]         public ActionResult SubmitInputTest(int id) {              //your code              //do stuff              return RedirectToAction("index");         } 

In your view (cshtml):

<form id="frmToSubmit" action="<controller>/SubmitInputTest">  <hidden id="id" name="id"/> </form> 

In your javascript:

$('#id').attr('value', [your ID Value]); $('#frmToSubmit').submit(); 
Read More

Saturday, February 25, 2017

How to setup multiple routing entries for socket?

Leave a Comment

I am very new to static routing, our client requested to implement static routing for sockets. When I googled I came across with rtentry to set routing information. When I opened this structure I saw the fields for static routing

struct sockaddr rt_dst;     /* Target address.  */ struct sockaddr rt_gateway;     /* Gateway addr (RTF_GATEWAY).  */ struct sockaddr rt_genmask;     /* Target network mask (IP).  */ 

But how can I setup multiple entry here? creating multiple rtentry and calling ioctl(FileDes, SIOCADDRT, &rtentry) will fix my problem?

int32_t FileDes = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP); for(auto RtEntry : RtEntriesList) {    ioctl(FileDes, SIOCADDRT, RtEntry)` } 

If I configure, how can I test this? It will be helpful if you can provide a link to know more about these things.

1 Answers

Answers 1

Finally I got my answers.

int32_t FileDes = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);  struct rtentry Route1; struct rtentry Route2; struct rtentry Route3;  // configure Route1 // configure Route2 // configure Route3  RtEntriesList.push_back(&Route1); RtEntriesList.push_back(&Route2); RtEntriesList.push_back(&Route3);  for(auto RtEntry : RtEntriesList) {    ioctl(FileDes, SIOCADDRT, RtEntry); } 

will work, we can create multple routing entries and add to the socket FD. and this will update the system wide routing table.

its similar to route add .. command

for testing i set the gateway as my PC ip address and started wireshark there. after setting routing configurations the given range of IP is routed to my PC. Thanks @osgx for the information that its actually setting the system wide routing table.

Read More

Thursday, February 2, 2017

Mapping multiple routes (controller) using a router

Leave a Comment

I am looking at danny vankooten router library here. This looks good (though not sure how will it handle project from medium to large, example an ecommerce site). Now, going by the example this is mapping

$router->map('GET','/', 'home.php', 'home'); $router->map('GET','/home/', 'home.php', 'home-home'); $router->map('GET','/plans/', 'plans.php', 'plans'); $router->map('GET','/about/', 'about.php', 'about'); $router->map('GET','/contact/', 'contact.php', 'contact'); $router->map('GET','/tos/', 'tos.html', 'tos'); 

Let say I have a scenario where my website has 20-30 static pages or near about 50 controllers with 2-3 action/method each.

How do I map them all. If I use the above method of mapping I will probably end up having more than 100 lines of mapping and this does not looks right.

I believe there should be a way or short cuts/wildcard like check if there is a page or controller available,then load it or else throw a 404.

How do I map all the routes the right way?.

PS. Giving out a bounty of 50 to anyone who is willing to answer on how to use the up said router using wildcard to match controller/method.

4 Answers

Answers 1

What you can do to lighten your router file is to move the route definition in a YAML file. You will still have many lines in your YAML but it will be more readable.

In your router.php file, use this code :

Don't forget to add the symfony YAML parser to your composer.json

use Symfony\Component\Yaml\Yaml; $yaml_file = 'routes.yaml'; $routes = Yaml::parse(file_get_contents($yaml_file)); foreach ($routes as $route_name => $params) {     $router->map($params[0],$params[1], $params[2].'#'.$params[3], $route_name); }   // match current request $match = $router->match(); 

Your file routes.yaml will look like this

index:      ["GET", "/", "home_controller", "display_item"] content:    ["GET", "/content/[:parent]/?[:child]?", "content_controller", "display_item"] article:    ["GET", "/article/[:page]", "article_controller", "display_item"] 

An other thing you can do to get smaller files is to separate your route definition in many small YAML files. For example, one for static files, one for admin area, one for front...

To do something like this, you have to change the router.php code to something like this :

use Symfony\Component\Yaml\Yaml; $yaml_files = ['front.yaml', 'static.yaml', 'admin.yaml']; foreach ($yaml_files as $yaml_file) {     $routes = Yaml::parse(file_get_contents($yaml_file));     foreach ($routes as $route_name => $params) {         $router->map($params[0],$params[1], $params[2].'#'.$params[3], $route_name);     }  }  // match current request $match = $router->match(); 

Danny Van Kooten also made PHP-Router which has a built-in support for YAML files. (If you look at the source code, you will see that he uses the Symfony parser so both methods are quite similar)

From the doc

YAML route definition

base_path: /blog  routes:   index: [/index, someClass.indexAction, GET]   contact: [/contact, someClass.contactAction, GET]   about: [/about, someClass.aboutAction, GET] 

Router.php

require __DIR__.'/vendor/autoload.php';  use PHPRouter\RouteCollection; use PHPRouter\Config; use PHPRouter\Router; use PHPRouter\Route;  $config = Config::loadFromFile(__DIR__.'/router.yaml'); $router = Router::parseConfig($config); $router->matchCurrentRequest(); 

Answers 2

in the library there is no function which do something like you wanted but there's an alternative way to do it, is to store those page on database by that you will have something like this below

//your query // "SELECT `method`, `route`, `page`, `name` FROM `static_pages` $pages = (query); //your executed query if(count($pages) > 0){   foreach($pages as $page){     $router->map($page['method'],$page['route'], $page['target'], (($page['name'] !== null || !empty($page['name']) ) ? $page['name'] : null));   } } 

I hope this helps

Answers 3

As part of the bootstrap phase tell your controllers to map themselves onto a router:

// bootstrap $router = new AltoRouter();  FooController::mapRoutes($router); BarController::mapRoutes($router); // etc. 

Each controller is allowed to produce however many routes it needs.

Answers 4

If you use a pre-built router like Silex you can do something like this:

$app->get('{route}', function($route) {     $dir = "/path/to/my/static/files/";     $file = $dir . $route . '.php';     if (file_exists($file)) {         require $file;     } else {         require '/path/to/custom/404.php';     } }); 

Note that Silex and many similar routers require routes to be by order of preference. When I need to use a router like this, I put it at the bottom so that it doesn't accidentally catch anything else.

Note that, if you want to build something like this custom, you can do this - keeping in mind I don't know what your code currently looks like or what logic you need - by substituting out your regular expression (in Silex's example, it is with curly brackets) and checking the $_SERVER['REQUEST_URI'] against your formulated regular expression.

If this is a custom application, you may not really need to over engineer this.

// routing class foreach ($routes as $route) {     if ($route != self::DEFAULT_ROUTE) {         // do your normal routing logic     } else {         // check if file exists (as with code above), else send to error 404     } } 

Then call with something like:

$router->map('GET',Router::DEFAULT_ROUTE, 'legacyRouter.php', 'legacy'); 
Read More

Friday, April 29, 2016

Search for view files in a custom location only for Specified Area in MVC 5

Leave a Comment

I'm looking to override the 'ViewEngine' for MVC5 in a way that first, it find my pages.. which already i failed.

Second, It only operate on a single Area {root}/{area}/{controller}/{action}/{etc.}

as so far as i googled it, i found several topic and answers, but they didn't fit my need. so i rather to ask it here, maybe i'm wrong with something...

public class CustomAreaViewEngine:RazorViewEngine {     public CustomAreaViewEngine()     {         var viewLocations = new[]         {             "~/App/pages/{1}/{0}.cshtml",             "~/App/pages/{1}/{0}.vbhtml"         };         AreaMasterLocationFormats = viewLocations;         AreaPartialViewLocationFormats = viewLocations;         AreaViewLocationFormats = viewLocations;     }      public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)     {          var viewEngineResult = base.FindPartialView(controllerContext, partialViewName, useCache);         return viewEngineResult;     }      public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)     {         controllerContext.RouteData.Values["controller"] = controllerContext.RouteData.Values["controller"].ToString().ToLower();          var viewEngineResult = base.FindView(controllerContext, viewName, masterName, useCache);         return viewEngineResult;     } } 

The method 'FindView' returns empty [first problem]

Global Config:

AreaRegistration.RegisterAllAreas(); ViewEngines.Engines.Add(new CustomAreaViewEngine()); // Look View Inside App/Pages/{1}/{0}.cshtml/.vbhtml 

My Hierarchy

Root --/App --/--/pages --/--/shared (but not that shared) --/... --/Area --/--/View --/--/--/Controller --/--/--/View(MVC BASED HIERARCHY, I Don't want to use in most case, and redirect to App) --/--/--/... --/--/... --/Controller --/View --/--/...(MVC BASED HIERARCHY) --/... 

EDITS:


EDIT1:


Changes i did due to @James Ellis-Jones answers:

Images: My Route Config: My Route Config Area Provided Route Config: Area Provided Route Config Global Config: Global Config My View Engine: My View Engine

still when i use http://localhost:1422/view/home/index i receive an error, which exist in my other home (View, related to the main controller, not the area controller.) it bring a wrong file.

Another Issue I Figured Out, Which Didn't Worked Too

My namespaces was wrong in last edit, and i changed them, but it didn't worked out too.

namespaces: new[] { "RavisHSB.Areas.View.Controllers" } 

EDIT2:


Changes i did due to @CarlosFernández answers:

I add ViewEngines.Engines.Clear(); it somehow went one step ahead. but still doesn't work.

New Global.aspx: My Global.aspx And i face this new error: The new Error

2 Answers

Answers 1

Try this: in RouteConfig.cs where you are setting up the route which links to a controller which you want to find the custom view location, add this:

var route = routes.MapRoute(<route params here>); route.DataTokens["area"] = "AreaName"; 

This will tell MVC that when you follow this route, you are going into area 'AreaName'. Then it will subsequently look for views in that area. Your custom ViewEngine will only affect view locations when MVC is looking for them in some area. Otherwise it won't have any effect, as the location format lists for areas are the only ones it overrides.

Answers 2

Try to customize this code for your engine

using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Web; using System.Web.Mvc;  namespace Partikan.Tuba.Core {      /*                                              TubaPortal Razor ViewEngine      *       * Path for Themes : ~/Site/Themes/{ThemeName}/Skin/{Culture}/{SkinName} ---> ~/Site/Themes/Default/Skin/fa-IR/default.csHtml      *  themeName, culture, name, controllerName, modulePath ,area      *       *       *       *       */      public class TubaPortalRazorViewEngine : RazorViewEngine     {         private static readonly List<string> EmptyLocations;          public TubaPortalRazorViewEngine()         {               MasterLocationFormats = new[]                 {                     "~/Site/Themes/{0}/Skin/{1}/{2}.cshtml",                     "~/Site/Themes/{0}/Skin/{2}.cshtml",                     "~/Views/Shared/{2}.cshtml"                 };             PartialViewLocationFormats = new[]                 {                     "~/Views/{1}/{0}.cshtml",                     "~/Views/Shared/{0}.cshtml",                                         "~/Site/Themes/{0}/Container/{2}.cshtml",                     "~/Plugins/{2}/{2}.cshtml",                     "~/Views/{3}/{2}.cshtml",                     "~/Views/Shared/{2}.cshtml"                 };              ViewLocationFormats = new[]                 {                                        "~/Site/Themes/{0}/Container/{2}.cshtml",                     "~/Plugins/{2}/{2}.cshtml",                     "~/Views/{3}/{2}.cshtml",                     "~/Views/Shared/{2}.cshtml"                 };              AreaViewLocationFormats = new[]                 {                     "~/Areas/{5}/Views/{3}/{2}.cshtml",                     "~/Areas/{5}/Views/Shared/{2}.cshtml"                 };             AreaMasterLocationFormats = new[]                 {                     "~/Areas/{5}/Views/{3}/{2}.cshtml",                     "~/Areas/{5}/Views/Shared/{2}.cshtml"                 };             AreaPartialViewLocationFormats = new[]                 {                     "~/Areas/{5}/Views/{3}/{2}.cshtml",                     "~/Areas/{5}/Views/Shared/{2}.cshtml"                 };             }          private static string GetThemeToUse(ControllerContext controllerContext)         {             if (controllerContext.HttpContext.Items == null) return "";             var themeName = controllerContext.HttpContext.Items["themeName"] == null ? "" :                 controllerContext.HttpContext.Items["themeName"] as string;                    return String.Format("{0}", themeName);         }         private static string GetCulture(ControllerContext controllerContext)         {             if (controllerContext.HttpContext.Items != null)             {                  var culture = controllerContext.HttpContext.Items["culture"] as string;                 if (string.IsNullOrEmpty(culture)) culture = "fa-IR";                 return String.Format("{0}", culture);             }             return "fa-IR";         }          protected override bool FileExists(ControllerContext controllerContext, string virtualPath)         {             try             {                 return System.IO.File.Exists(controllerContext.HttpContext.Server.MapPath(virtualPath));             }             catch (HttpException exception)             {                 if (exception.GetHttpCode() != 0x194)                 {                     throw;                 }                 return false;             }             catch             {                 return false;             }         }          public override ViewEngineResult FindView(ControllerContext controllerContext, string viewName, string masterName, bool useCache)         {             var strArray = new List<string>();             var strArray2 = new List<string>();                        if (controllerContext == null)             {                 throw new ArgumentNullException("controllerContext");             }             if (string.IsNullOrEmpty(viewName))             {                 throw new ArgumentException("viewName must be specified.", "viewName");             }                var themeName = GetThemeToUse(controllerContext);              var culture = GetCulture(controllerContext);              var controllerName = controllerContext.RouteData.GetRequiredString("controller");             var modulePath = controllerContext.RouteData.Values.Keys.Contains("ModulePath") ? controllerContext.RouteData.GetRequiredString("ModulePath") : "";             var viewPath = "";              var viewLocation = ViewLocationFormats;             var masterLocation = MasterLocationFormats;             var area = "";             if (controllerContext.RouteData.DataTokens.Keys.Any(x => x.ToLower() == "area"))             {                 area = controllerContext.RouteData.DataTokens.FirstOrDefault(x => x.Key.ToLower() == "area").Value.ToString();                  viewLocation = AreaViewLocationFormats;                 masterLocation = AreaMasterLocationFormats;             }              if (IsExternalWidgetView(viewName))             {                 viewPath = viewName;             }             else             {                 viewPath = GetPath(controllerContext, viewLocation, area, viewName, themeName, controllerName, culture, modulePath, "TubaSite_View", useCache, strArray);             }                var masterPath = GetPath(controllerContext, masterLocation, area, masterName, themeName, controllerName, culture, modulePath, "TubaSite_Master", useCache, strArray2);              if (!string.IsNullOrEmpty(viewPath) && (!string.IsNullOrEmpty(masterPath) || string.IsNullOrEmpty(masterName)))             {                 return new ViewEngineResult(this.CreateView(controllerContext, viewPath, masterPath), this);             }             if (string.IsNullOrEmpty(masterPath) && strArray == null)             {                 throw new Exception(String.Format("Skin {0} {1} in {2} Not Found .", themeName, masterName, masterPath));             }             if (string.IsNullOrEmpty(viewPath))             {                 throw new Exception(String.Format("Page Not Found - {0} {1} {2}", themeName, masterName, masterPath));             }             return new ViewEngineResult(strArray.Union<string>(strArray2));         }         public override ViewEngineResult FindPartialView(ControllerContext controllerContext, string partialViewName, bool useCache)         {             var strArray = new List<string>();             if (controllerContext == null)             {                 throw new ArgumentNullException("controllerContext");             }             if (string.IsNullOrEmpty(partialViewName))             {                 throw new ArgumentException("partialViewName must be specified.", "partialViewName");             }               var themeName = GetThemeToUse(controllerContext);             var modulePath = controllerContext.RouteData.Values.Keys.Contains("ModulePath") ? controllerContext.RouteData.GetRequiredString("ModulePath") : "";              var requiredString = controllerContext.RouteData.GetRequiredString("controller");              var partialViewLocation = PartialViewLocationFormats;             var area = "";             if (controllerContext.RouteData.DataTokens.Keys.Any(x => x.ToLower() == "area"))             {                 area = controllerContext.RouteData.DataTokens.FirstOrDefault(x => x.Key.ToLower() == "area").Value.ToString();                 partialViewLocation = AreaPartialViewLocationFormats.Union(PartialViewLocationFormats).ToArray();             }              var partialViewPath = "";             if (IsExternalWidgetView(partialViewName))             {                 partialViewPath = partialViewName;             }             else             {                 partialViewPath = GetPath(controllerContext, partialViewLocation, area, partialViewName, themeName, requiredString, "fa-IR", modulePath, "TubaSite_Partial", false, strArray);             }             return string.IsNullOrEmpty(partialViewPath) ? new ViewEngineResult(strArray) : new ViewEngineResult(CreatePartialView(controllerContext, partialViewPath), this);         }           private string GetPath(ControllerContext controllerContext, string[] locations, string area,                 string name, string themeName, string controllerName, string culture, string modulePath,                 string cacheKeyPrefix, bool useCache, List<string> searchedLocations)         {             searchedLocations = EmptyLocations;             if (string.IsNullOrEmpty(name))             {                 return string.Empty;             }              if ((locations == null) || (locations.Length == 0))             {                 throw new InvalidOperationException("هـیچ مسـیـری بـرای جستجو تعریف نشده است.");             }              var flag = IsSpecificPath(name);             var key = CreateCacheKey(cacheKeyPrefix, name, flag ? string.Empty : controllerName, themeName);             if (useCache)             {                 var viewLocation = ViewLocationCache.GetViewLocation(controllerContext.HttpContext, key);                 if (viewLocation != null)                 {                     return viewLocation;                 }             }             if (!flag)             {                 return string.IsNullOrEmpty(culture) ?                         GetPathFromGeneralName(controllerContext, locations, area, name, controllerName, themeName,  modulePath, key, searchedLocations) :                         GetPathFromGeneralName(controllerContext, locations, area, name, controllerName, themeName, culture, modulePath, key, searchedLocations);              }             return GetPathFromSpecificName(controllerContext, name, key, searchedLocations);         }          private static bool IsExternalWidgetView(string name)         {              return name.StartsWith("~/ExternalWidget", StringComparison.InvariantCultureIgnoreCase);         }          private static bool IsSpecificPath(string name)         {             var ch = name[0];             if (ch != '~')             {                 return (ch == '/');             }             return true;         }          private string CreateCacheKey(string prefix, string name, string controllerName, string themeName)         {             return string.Format(CultureInfo.InvariantCulture,                     ":ViewCacheEntry:{0}:{1}:{2}:{3}:{4}", GetType().AssemblyQualifiedName, prefix, name, controllerName, themeName);         }          private string GetPathFromGeneralName(ControllerContext controllerContext, IEnumerable<string> locations, string area, string name,                 string controllerName, string themeName,  string culture, string modulePath, string cacheKey, List<string> searchedLocations)         {             if (locations == null) throw new ArgumentNullException("locations");             if (searchedLocations == null) searchedLocations = new List<string>();              var virtualPath = string.Empty;                      var locationData =                 locations.Select(                     t =>                     string.Format(CultureInfo.InvariantCulture, t,                                                 string.IsNullOrEmpty(culture)                                                     ? new object[] { name, controllerName }                                                     : new object[] {  themeName, culture, name, controllerName, modulePath, area })).ToList();             foreach (var str2 in locationData)             {                 if (FileExists(controllerContext, str2))                 {                     virtualPath = str2;                     ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, cacheKey, virtualPath);                     return virtualPath;                 }                 searchedLocations.Add(str2);             }             return virtualPath;         }          private string GetPathFromGeneralName(ControllerContext controllerContext, IEnumerable<string> locations, string area, string name,                 string controllerName, string themeName,  string modulePath, string cacheKey, List<string> searchedLocations)         {             return GetPathFromGeneralName(controllerContext, locations, area, name, controllerName, themeName, "", modulePath, cacheKey, searchedLocations);         }          private string GetPathFromSpecificName(ControllerContext controllerContext, string name, string cacheKey, List<string> searchedLocations)         {             var virtualPath = name;             if (!FileExists(controllerContext, name))             {                 virtualPath = string.Empty;                 searchedLocations = new List<string>() { name };             }             ViewLocationCache.InsertViewLocation(controllerContext.HttpContext, cacheKey, virtualPath);             return virtualPath;         }     }  } 
Read More

Thursday, April 21, 2016

Using Rails 5 (the API flag) and getting no route error despite route declared

Leave a Comment

This is my controller:

class Api::V1::UsersController < ApplicationController   respond_to :json    def show     respond_with User.find(params[:id])   end end 

This is my routes.rb

require 'api_constraints'  Rails.application.routes.draw do   devise_for :users   # Api definition   namespace :api, defaults: { format: :json }, constraints: { subdomain: 'api' }, path: '/' do     scope module: :v1, constraints: ApiConstraints.new(version: 1, default: true) do       resources :users, :only => [:show]     end   end end 

This is my lib/api_constraints.rb

class ApiConstraints   def initialize(options)     @version = options[:version]     @default = options[:default]   end    def matches?(req)     @default || req.headers['Accept'].include?("application/vnd.myapp.v#{@version}")   end end 

I added a record to my DB as can be seen here:

[3] pry(main)> User.all   User Load (0.4ms)  SELECT "users".* FROM "users" => [#<User:0x007fbdb31079f8   id: 1,   email: "abc@test.com",   encrypted_password: "$2a$11$rvOrK1bmuuNwwc78ERxG3eCrKiUu9NTZsJ/nmirqb.3yRBHYUK69S",   reset_password_token: nil,   reset_password_sent_at: nil,   remember_created_at: nil,   sign_in_count: 0,   current_sign_in_at: nil,   last_sign_in_at: nil,   current_sign_in_ip: nil,   last_sign_in_ip: nil,   created_at: Mon, 11 Apr 2016 10:35:39 UTC +00:00,   updated_at: Mon, 11 Apr 2016 10:35:39 UTC +00:00>] 

Yet this is the error I get in my rails console:

ActionController::RoutingError (No route matches [GET] "/users/1"):  actionpack (5.0.0.beta3) lib/action_dispatch/middleware/debug_exceptions.rb:53:in `call' web-console (3.1.1) lib/web_console/middleware.rb:131:in `call_app' web-console (3.1.1) lib/web_console/middleware.rb:28:in `block in call' web-console (3.1.1) lib/web_console/middleware.rb:18:in `catch' web-console (3.1.1) lib/web_console/middleware.rb:18:in `call' actionpack (5.0.0.beta3) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call' railties (5.0.0.beta3) lib/rails/rack/logger.rb:36:in `call_app' railties (5.0.0.beta3) lib/rails/rack/logger.rb:24:in `block in call' activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:70:in `block in tagged' activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:26:in `tagged' activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:70:in `tagged' railties (5.0.0.beta3) lib/rails/rack/logger.rb:24:in `call' actionpack (5.0.0.beta3) lib/action_dispatch/middleware/request_id.rb:24:in `call' rack (2.0.0.alpha) lib/rack/runtime.rb:22:in `call' activesupport (5.0.0.beta3) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call' actionpack (5.0.0.beta3) lib/action_dispatch/middleware/load_interlock.rb:13:in `call' actionpack (5.0.0.beta3) lib/action_dispatch/middleware/static.rb:136:in `call' rack (2.0.0.alpha) lib/rack/sendfile.rb:111:in `call' railties (5.0.0.beta3) lib/rails/engine.rb:522:in `call' puma (3.2.0) lib/puma/configuration.rb:227:in `call' puma (3.2.0) lib/puma/server.rb:561:in `handle_request' puma (3.2.0) lib/puma/server.rb:406:in `process_client' puma (3.2.0) lib/puma/server.rb:271:in `block in run' puma (3.2.0) lib/puma/thread_pool.rb:111:in `block in spawn_thread' 

And this is what I see in my browser:

{"status":404,"error":"Not Found","exception":"#\u003cActionController::RoutingError: No route matches [GET] \"/users/1\"\u003e","traces":{"Application Trace":[],"Framework Trace":[{"id":0,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/debug_exceptions.rb:53:in `call'"},{"id":1,"trace":"web-console (3.1.1) lib/web_console/middleware.rb:131:in `call_app'"},{"id":2,"trace":"web-console (3.1.1) lib/web_console/middleware.rb:28:in `block in call'"},{"id":3,"trace":"web-console (3.1.1) lib/web_console/middleware.rb:18:in `catch'"},{"id":4,"trace":"web-console (3.1.1) lib/web_console/middleware.rb:18:in `call'"},{"id":5,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'"},{"id":6,"trace":"railties (5.0.0.beta3) lib/rails/rack/logger.rb:36:in `call_app'"},{"id":7,"trace":"railties (5.0.0.beta3) lib/rails/rack/logger.rb:24:in `block in call'"},{"id":8,"trace":"activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:70:in `block in tagged'"},{"id":9,"trace":"activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:26:in `tagged'"},{"id":10,"trace":"activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:70:in `tagged'"},{"id":11,"trace":"railties (5.0.0.beta3) lib/rails/rack/logger.rb:24:in `call'"},{"id":12,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/request_id.rb:24:in `call'"},{"id":13,"trace":"rack (2.0.0.alpha) lib/rack/runtime.rb:22:in `call'"},{"id":14,"trace":"activesupport (5.0.0.beta3) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'"},{"id":15,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/load_interlock.rb:13:in `call'"},{"id":16,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/static.rb:136:in `call'"},{"id":17,"trace":"rack (2.0.0.alpha) lib/rack/sendfile.rb:111:in `call'"},{"id":18,"trace":"railties (5.0.0.beta3) lib/rails/engine.rb:522:in `call'"},{"id":19,"trace":"puma (3.2.0) lib/puma/configuration.rb:227:in `call'"},{"id":20,"trace":"puma (3.2.0) lib/puma/server.rb:561:in `handle_request'"},{"id":21,"trace":"puma (3.2.0) lib/puma/server.rb:406:in `process_client'"},{"id":22,"trace":"puma (3.2.0) lib/puma/server.rb:271:in `block in run'"},{"id":23,"trace":"puma (3.2.0) lib/puma/thread_pool.rb:111:in `block in spawn_thread'"}],"Full Trace":[{"id":0,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/debug_exceptions.rb:53:in `call'"},{"id":1,"trace":"web-console (3.1.1) lib/web_console/middleware.rb:131:in `call_app'"},{"id":2,"trace":"web-console (3.1.1) lib/web_console/middleware.rb:28:in `block in call'"},{"id":3,"trace":"web-console (3.1.1) lib/web_console/middleware.rb:18:in `catch'"},{"id":4,"trace":"web-console (3.1.1) lib/web_console/middleware.rb:18:in `call'"},{"id":5,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/show_exceptions.rb:31:in `call'"},{"id":6,"trace":"railties (5.0.0.beta3) lib/rails/rack/logger.rb:36:in `call_app'"},{"id":7,"trace":"railties (5.0.0.beta3) lib/rails/rack/logger.rb:24:in `block in call'"},{"id":8,"trace":"activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:70:in `block in tagged'"},{"id":9,"trace":"activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:26:in `tagged'"},{"id":10,"trace":"activesupport (5.0.0.beta3) lib/active_support/tagged_logging.rb:70:in `tagged'"},{"id":11,"trace":"railties (5.0.0.beta3) lib/rails/rack/logger.rb:24:in `call'"},{"id":12,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/request_id.rb:24:in `call'"},{"id":13,"trace":"rack (2.0.0.alpha) lib/rack/runtime.rb:22:in `call'"},{"id":14,"trace":"activesupport (5.0.0.beta3) lib/active_support/cache/strategy/local_cache_middleware.rb:28:in `call'"},{"id":15,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/load_interlock.rb:13:in `call'"},{"id":16,"trace":"actionpack (5.0.0.beta3) lib/action_dispatch/middleware/static.rb:136:in `call'"},{"id":17,"trace":"rack (2.0.0.alpha) lib/rack/sendfile.rb:111:in `call'"},{"id":18,"trace":"railties (5.0.0.beta3) lib/rails/engine.rb:522:in `call'"},{"id":19,"trace":"puma (3.2.0) lib/puma/configuration.rb:227:in `call'"},{"id":20,"trace":"puma (3.2.0) lib/puma/server.rb:561:in `handle_request'"},{"id":21,"trace":"puma (3.2.0) lib/puma/server.rb:406:in `process_client'"},{"id":22,"trace":"puma (3.2.0) lib/puma/server.rb:271:in `block in run'"},{"id":23,"trace":"puma (3.2.0) lib/puma/thread_pool.rb:111:in `block in spawn_thread'"}]}} 

Edit 1

This is my rake routes

$ rake routes [DEPRECATION] `last_comment` is deprecated.  Please use `last_description` instead. [DEPRECATION] `last_comment` is deprecated.  Please use `last_description` instead. [DEPRECATION] `last_comment` is deprecated.  Please use `last_description` instead.                   Prefix Verb   URI Pattern                    Controller#Action         new_user_session GET    /users/sign_in(.:format)       devise/sessions#new             user_session POST   /users/sign_in(.:format)       devise/sessions#create     destroy_user_session DELETE /users/sign_out(.:format)      devise/sessions#destroy            user_password POST   /users/password(.:format)      devise/passwords#create        new_user_password GET    /users/password/new(.:format)  devise/passwords#new       edit_user_password GET    /users/password/edit(.:format) devise/passwords#edit                          PATCH  /users/password(.:format)      devise/passwords#update                          PUT    /users/password(.:format)      devise/passwords#update cancel_user_registration GET    /users/cancel(.:format)        devise/registrations#cancel        user_registration POST   /users(.:format)               devise/registrations#create    new_user_registration GET    /users/sign_up(.:format)       devise/registrations#new   edit_user_registration GET    /users/edit(.:format)          devise/registrations#edit                          PATCH  /users(.:format)               devise/registrations#update                          PUT    /users(.:format)               devise/registrations#update                          DELETE /users(.:format)               devise/registrations#destroy                 api_user GET    /users/:id(.:format)           api/v1/users#show {:format=>:json, :subdomain=>"api"} 

Edit 2

This is my application controller:

class ApplicationController < ActionController::API end 

Edit 3

This is my users_controller_spec.rb test that actually passes:

require 'rails_helper'  describe Api::V1::UsersController do   before(:each) { request.headers['Accept'] = "application/vnd.myapp.v1" }    describe "GET #show" do     before(:each) do       @user = FactoryGirl.create :user       get :show, id: @user.id, format: :json     end      it "returns the information about a user on a hash" do       user_response = JSON.parse(response.body, symbolize_names: true)       expect(user_response[:email]).to eql @user.email     end      it { should respond_with 200 }   end  end 

This is the result:

$ rspec spec/controllers DEPRECATION WARNING: use_transactional_fixtures= is deprecated and will be removed from Rails 5.1 (use use_transactional_tests= instead). (called from <top (required)> at /myapp/spec/controllers/api/v1/users_controller_spec.rb:3) DEPRECATION WARNING: ActionController::TestCase HTTP request methods will accept only keyword arguments in future Rails versions.  Examples:  get :show, params: { id: 1 }, session: { user_id: 1 } process :update, method: :post, params: { id: 1 }  (called from block (3 levels) in <top (required)> at /myapp/spec/controllers/api/v1/users_controller_spec.rb:9) DEPRECATION WARNING: ActionController::TestCase HTTP request methods will accept only keyword arguments in future Rails versions.  Examples:  get :show, params: { id: 1 }, session: { user_id: 1 } process :update, method: :post, params: { id: 1 }  (called from block (3 levels) in <top (required)> at /myapp/spec/controllers/api/v1/users_controller_spec.rb:9) .DEPRECATION WARNING: ActionController::TestCase HTTP request methods will accept only keyword arguments in future Rails versions.  Examples:  get :show, params: { id: 1 }, session: { user_id: 1 } process :update, method: :post, params: { id: 1 }  (called from block (3 levels) in <top (required)> at /myapp/spec/controllers/api/v1/users_controller_spec.rb:9) DEPRECATION WARNING: ActionController::TestCase HTTP request methods will accept only keyword arguments in future Rails versions.  Examples:  get :show, params: { id: 1 }, session: { user_id: 1 } process :update, method: :post, params: { id: 1 }  (called from block (3 levels) in <top (required)> at /myapp/spec/controllers/api/v1/users_controller_spec.rb:9) .  Finished in 0.41411 seconds (files took 3.33 seconds to load) 2 examples, 0 failures 

1 Answers

Answers 1

The problem is that your route has a constraint requiring a subdomain of api. So http://api.lvh.me:3000/users/1.json will work, but not http://localhost:3000/users/1.json or http://lvh.me:3000/users/1.json.

You should change your Ajax call to use an api subdomain. You can also confirm this by writing a request test (not a controller test), and see that it gets a 200 when using an api subdomain, and a 404 otherwise.

Read More

Monday, March 28, 2016

Programmatically get routes in Play! Framework 2.5.x

Leave a Comment

In the play-swagger module, we used the play.routes.compiler.RoutesFileParser to get all registered routes from Play and further parse them to an API documentation:

val parsedRoutes = RoutesFileParser.parse(new File(app.classloader.getResource(routesFile).toURI)) val routes = parsedRoutes.right.get.collect {   case (route: PlayRoute) => {     logger.debug(s"Adding route '$route'")     Seq(route.copy(path = route.path.copy(parts = StaticPart(prefix + "/") +: route.path.parts)))   }   case (include: PlayInclude) => {     logger.debug(s"Processing route include $include")     parseRoutesHelper(playRoutesClassNameToFileName(include.router), include.prefix)   } }.flatten 

This results in the following error: java.lang.NoClassDefFoundError: play/routes/compiler/RoutesFileParser

It seems that the RoutesFileParser became private in Play! 2.5.

What is the correct way to fetch all Play routes like in the example above?

2 Answers

Answers 1

This is definitely a dependency problem. Check the dependencyTree.

If it's not already there, then add the following to the build file:

"com.typesafe.play" %% "routes-compiler" % "2.5.0" 

Then this will compile and run nicely:

val routesURI = app.classloader.getResource("routes").toURI val parsedRoutes = play.routes.compiler.RoutesFileParser.parse(new File(routesURI)) println(parsedRoutes) 

(where app is a running instance of play.api.Application)

Answers 2

When looking through the sourcecode of Play, I found that I can use the following:

class HomeController @Inject() (router: Provider[Router]) { ....     router.get().documentation.foreach(println) .... } 

This will print out String tuples with HTTP method, path, method invocation. This is how the routes on the DEV 404 page are rendered.

Read More