ASP.NET 'Friendly URL' module - not working for root URL - asp.net

I am successfully using the 'Friendly URL' module in ASP.NET 4.5
In route config I can add a route like this:
routes.MapPageRoute("mypage", "mypage/{mypageName}", "~/mypage.aspx");
for a URL like this:
mysite.com/mypage/hello
in the page 'mypage.aspx' I can get URL segments like this:
using Microsoft.AspNet.FriendlyUrls;
// Get URL segments
IList<string> segments = Request.GetFriendlyUrlSegments();
if (segments.Count > 0)
{
// Get first segment
string url = segments[0];
}
However, I cannot get this working for root URL's. e.g. 'my site.com/ttee'
I want to get 'ttee' and pass it into a page. But 'Request.GetFriendlyUrlSegments()' returns 0 for the root.
How best can I do this?

routes.MapPageRoute("mypage", "mypage/{mypageName}", "~/mypage.aspx");
This will work only for URLs in this format:
www.example.com/mypage/changingparthere
If you want to make it
www.example.com/changablemypage
Set it to:
routes.MapPageRoute("mypage", "{mypageName}", "~/mypage.aspx");
But as you can see, it will catch literally everything. So make sure it is the last routing on Global.asax.

Related

.Net core Routing URLEncoded URL not working

I have a .Net core 2.2 WebAPI that works perfectly fine with "normal" style URLs e.g. /api/controller/action/param etc. I have a 3rd party service that does a POST to this API with a URL encoded path and the Asp.Net routing fails to route this request correctly.
The controller is at: .../api/file/uploadFile/{filename}
The POST from the 3rd party is:
".../api%2Ffile%2FuploadFile%2FMaintenanceReport_2019_08_05_17_11_10.html.gz".
Replacing the %2F in the path appears to work as expected:
".../api/file/uploadFile/MaintenanceReport_2019_08_05_17_11_10.html.gz"
The filename is: "MaintenanceReport_2019_08_05_17_11_10.html.gz"
Placing a Route Attribute with %2F instead of "/" sort of works, but looks very messy.
The filename passed into the path is also not resolving correctly as a parameters. I suspect this is due to the file extension being included.
I've searched the net and did not find anything related jumping out at me. Any suggestions/ideas?
[Route("api/[controller]/[action]")]
[Route("api%2F[controller]%2F[action]")]
public class FileController : Controller
{
...
}
I would have thought that the .Net core routing engine would detect the path
The default path separator in the url generated by the route is / .The issue seems that the separator before the parameter which is as part of the path value is not recognized or missing .
If you request the url like .../api%2Ffile%2FuploadFile%2FMaintenanceReport_2019_08_05_17_11_10.html.gz , you could try to use URL Rewriting Middleware like below :
In Configure
app.UseRewriter(new RewriteOptions()
.Add(RewriteRouteRules.ReWriteRequests)
);
2.Custom a class containing ReWriteRequests
public class RewriteRouteRules
{
public static void ReWriteRequests(RewriteContext context)
{
var request = context.HttpContext.Request;
if (request.Path.Value.Contains("%2F", StringComparison.OrdinalIgnoreCase))
{
context.HttpContext.Request.Path = context.HttpContext.Request.Path.Value.Replace("%2F", "/");
}
}
}
Reference: https://learn.microsoft.com/en-us/aspnet/core/fundamentals/url-rewriting?view=aspnetcore-2.1&tabs=aspnetcore2x

Symfony: How encode / in URL parameter?

I want to build RESTful API with URLs something like:
First route: http://example.com/api/{element_name}/aaa/{related_name} and
Second route: http://example.com/api/{element_name}/bbb/{related_name}.
Everything is simple and easy when element_name is integer or simple text.
Things get complicated when parameter {element_name} has "/" char in the name, because even if I encode / by %2f (url encode) routing will decode %2f before process routes.
For example when I want to generate URL to first route and I have {element_name} = xyz and {related_name} = ooo then the URL will be http://example.com/api/xyz/aaa/ooo and it's OK.
But when I have {element_name} = xyz/bbb and {related_name} = ooo then the URL should be: http://example.com/api/xyz%2fbbb/aaa/ooo but routing first will decode url and make: http://example.com/api/xyz/bbb/aaa/ooo and it isn't OK because doesn't match to first route.
How I should do that?
All you need to do is to add requirement while configuring the routes in your controller. Like so :
class DefaultController
{
/**
* #Route("/share/{token}", name="share", requirements={"token"=".+"})
*/
public function share($token)
{
// ...
}
}
it's explained in the SF doc: http://symfony.com/doc/current/routing/slash_in_parameter.html

ASP.net MVC 5 Route with two parameter

I want create web application with 2 parameter. Add this Code to RegisterRoutes function:
routes.MapRoute(
"pageroute",
"page/{pageid}/{pagename}",
new { controller = "page", action = "Index", pageid = "", pagename = "" }
);
and add this method in pageController:
public ActionResult Index(int pageid,string pagename)
{
return View();
}
Now when i running application with this parameter
http://localhost:1196/page/4/Pagename
Application run successfully but when running with this parameter
http://localhost:1196/page/4/Pagename.html
Application return 404 error
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
while add .html in parameter return 404 error. why?
Because by default HTML files are not being served through MVC/IIS.
Your application looks for a physical file named Pagename.html and cannot find it there. Hence - 404.
To make it work, you need to setup your IIS to catch requests for files with HTML extension and pass this request to MVC.
EDIT: Here is a similar question where OP found a solution by switching "Managed Pipeline Mode" to "Classic".
Try changing the Route to:
routes.MapRoute(
"pageroute",
"page/{pageid}/{*pagename}",
new { controller = "page", action = "Index", pageid = "", pagename = "" }
);
This will then match everything as in page/1/* so the .html should go via this route.
I was unable to reproduce an issue where a .html file gave a 404 using a scenario similar to the question, so there may be some other routing issue or IIS configuration causing this.

WordPress custom url without parameters

I have create a custom url for my plugin in WordPress that I don't like to have any argument.
Lets say that my URL us that
http://www.mysite.ext/test/
How can I know from my code that the users in on /test/ and not in any other page from within my code ?
This is my code:
add_action('init', 'add_rewrite_rule');
function add_rewrite_rule()
{
add_rewrite_rule('test/?', 'index.php', 'top');
}
if you only want to test whether the current pages ends with /test/, can you do it in php like this:
//get host name, this returns www.mysite.ext
host = $_SERVER['HTTP_HOST'];
//get full path, this returns /test
$script = $_SERVER['SCRIPT_NAME'];
This is not test, but worth trying.

Routing with a Guid in ASP.NET MVC

I have a url which will take the following form:
/AuditReview/Review/15d49a66-5c11-492c-921f-9e1700bd2618
I cannot get this to route, my routes look like this:
MvcRoute.MappUrl("{controller}.mvc.aspx/{action}/{auditEventUid}")
.WithDefaults(new {controller = "AuditReview", action = "Review"})
.WithConstraints(new { controller = "AuditReview", action ="Review", auditEventUid = new GuidConstraint() });
MvcRoute.MappUrl("admin/{controller}.mvc.aspx/{action}")
.WithDefaults(new { controller = "audit", action = "index" })
.WithConstraints(new{controller = "audit"})
.AddWithName("admin", routes);
MvcRoute.MappUrl("{controller}.mvc.aspx/{action}")
.WithDefaults(new {action = "Index"})
.AddWithName("Default", routes);
Can anyone suggest a route to make this work?
Your current routing rules would require you to access the url using:
/AuditReview.mvc.aspx/Review/15d49a66-5c11-492c-921f-9e1700bd2618
If you're running IIS 7 or have enough access to the server to install wildcard mapping you can just remove the .mvc.aspx from your routing rules and your original url will work.
This should work - I am able to map a simpler scenario fine. Can you get this scenario to work with a simpler route (e.g. the default "{controller}.mvc/{action}/{id}" route)?
Have you tried removing the GuidConstraint or testing to make sure that the GuidConstraint works? Perhaps that is not working properly.

Resources