RouteConfig and filename with extension - MVC5 - asp.net-mvc

I have the following URLs:
/Meetings/doc1.pdf
/Meetings/doc2.pdf
I tried to set up the following in my RoouteConfig
var route = routes.MapRoute(
name: "RedirectMeetingDocs",
url: "Meetings/{filename}",
defaults: new { action= "GetAttachmentByName", controller = "Generic" },
constraints: new { filename = #"(.*?)\.(pdf|ppt)" }
);
With the following function:
[HttpGet]
public ActionResult GetAttachmentByName(string fileName)
{
...
}
However, it nevers work and I keep getting a 404 error.
I also tried:
var route = routes.MapRoute(
name: "RedirectMeetingDocs",
url: "Meetings/{filename}.{extension}",
defaults: new { action= "GetAttachmentByName", controller = "Generic" },
constraints: new { filename = new AlphaRouteConstraint(), extension = new AlphaRouteConstraint() }
);
with
public ActionResult GetAttachmentByName(string fileName, string extension)
{
But nothing works.
Any advices?

Ok I solve it by adding the following in my Web.config:
<add name="IATTCRedirectOldMeetingFiles" path="meetings/*" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
Now, both RouteConfig shown above work.

Related

Custom route that match a single specific url

In my mvc app, I want to dynamically generate a specific url :
https://myapp.corp.com/.well-known/microsoft-identity-association.json
This endpoint should produce a small file based on values in the web.config file. So I created this controller :
public class HostingController : Controller
{
// GET: Hosting
[OutputCache(Duration = 100, VaryByParam = "none")]
public ActionResult MicrosoftIdentityAssociation() => Json(new
{
associatedApplications = new[]
{
new { applicationId = WebConfigurationManager.AppSettings.Get("ClientId") }
}
});
}
And I changed the routing configuration like this :
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Azure domain registration",
".well-known/microsoft-identity-association.json",
new { controller = "Hosting", action= "MicrosoftIdentityAssociation" }
);
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
I expect the url to produce json like :
{
"associatedApplications": [
{
"applicationId": "1562019d-44f7-4a9d-9833-64333f52181d"
}
]
}
But when I target the url, I got a 404 error.
What's wrong ? how to fix ?
You can use a route attribute:
[Route("~/.well-known/microsoft-identity-association.json")]
[OutputCache(Duration = 100, VaryByParam = "none")]
public ActionResult MicrosoftIdentityAssociation()
{
..... your code
}
It was tested in postman.
Asp.Net MVC can't create route that have extension. I had to edit my Web.config to plug the MVC framework on this very specific file.
Specifically :
<system.webServer>
<handlers>
<add name="Azure domain verifier"
path=".well-known/microsoft-identity-association.json"
verb="GET" type="System.Web.Handlers.TransferRequestHandler"
preCondition="integratedMode,runtimeVersionv4.0" responseBufferLimit="0"
/>
</handlers>
</system.webServer>
From this point, I was able to route to my custom controller action using either routeconfig.cs file or the [RouteAttribute]

How do I setup default routes that match just parameters?

This is how I want my routes to work:
http://example.com -> UpdatesController.Query()
http://example.com/myapp/1.0.0.0 -> UpdatesController.Fetch("myapp", "1.0.0.0")
http://example.com/myapp/1.0.0.1 -> UpdatesController.Fetch("myapp", "1.0.0.1")
http://example.com/other/2.0.0.0 -> UpdatesController.Fetch("other", "2.0.0.0")
My controller looks like this:
public class UpdatesController : Controller {
public ActionResult Query() { ... }
public ActionResult Fetch(string name, string version) { ... }
}
The route config that I've tried is this:
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Fetch",
url: "{name}/{version}",
defaults: new { controller = "Updates", action = "Fetch" },
constraints: new { name = #"^.+$", version = #"^\d+(?:\.\d+){1,3}$" }
);
routes.MapRoute(
name: "Query",
url: "",
defaults: new { controller = "Updates", action = "Query" }
);
But only the first example works. The others that should call the Fetch action method all fail with 404.
What am I doing wrong?
(I've also tried it without the route constraints, but there is no difference)
add following code to web.config, because your url contains dot value (1.0.0.0)
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
Another way
you can do it via Attribute routing.
to enable attribute routing, write below code in RouteConfig.cs
routes.MapMvcAttributeRoutes();
In controller your Action look like this
[Route("")]
public ActionResult Query()
{
return View();
}
[Route("{name}/{version}")]
public ActionResult Fetch(string name, string version)
{
return View();
}

MVC custom URL routing

I have a route configured like
routes.MapRoute(
name: "Default",
url: "TEST/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
It works fine to redirect to respective controller and actions.
I want to add another redirection on TEST so that if somebody uses www.mysite.com/TEST, it should redirect www.mysite.com/Test/Home instead of giving 403- Forbidden: Access is denied error.
I'm trying like this but could not achieve it.
routes.MapRoute(
name: "AnotherDefault",
url: "TEST",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
Basically, what I'm trying to do is to redirect from www.mysite.com or www.mysite.com/TEST to www.mysite.com/TEST/Home
To add to the confusion, I also had a physical folder TEST in my application root. Just wondering if keeping another web.config in there would solve? I tried but of no luck
Please advise what i'm missing here. Thanks
After some experiment I have found that the physical folder TEST is causing redirection rule to fail. I changed my route to TEST1 in URL instead of TEST, it worked. But, I can't rename TEST folder. Please advise
Please set the property RouteExistingFiles to true above the Route configurations
public static void RegisterRoutes(RouteCollection routes)
{
routes.RouteExistingFiles = true;
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "TEST/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
This should allow you to keep the name of folder and also the route name to be "TEST". Let me know how it works out for you
Keep using the first route:
routes.MapRoute(
name: "Default",
url: "TEST/{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
and add this in your Web.config:
<system.webServer>
<modules runAllManagedModulesForAllRequests="true"></modules>
<handlers>
<remove name="UrlRoutingHandler"/>
</handlers>
</system.webServer>
We Can manage url routing by validate from database.
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
// here i pass my parameter like wwww.abc.com/country-state-city
routes.MapLocalizedRoute("SeoFriendlyUrl",
"{SeoFriendlyName}",
new { controller = "Company", action = "Index" },
new[] { "MigrationTest.Controllers" });
// it is default
routes.MapRoute( name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
public static class LocalizedRouteExtensionMethod
{
public static Route MapLocalizedRoute(this RouteCollection routes, string name, string url, object defaults, string[] namespaces)
{
return MapLocalizedRoute(routes, name, url, defaults, null /* constraints */, namespaces);
}
public static Route MapLocalizedRoute(this RouteCollection routes, string name, string url, object defaults, object constraints, string[] namespaces)
{
if (routes == null)
{
throw new ArgumentNullException("routes");
}
if (url == null)
{
throw new ArgumentNullException("url");
}
var route = new clsRouteData(url, new MvcRouteHandler())
{
Defaults = new RouteValueDictionary(defaults),
Constraints = new RouteValueDictionary(constraints),
DataTokens = new RouteValueDictionary()
};
if ((namespaces != null) && (namespaces.Length > 0))
{
route.DataTokens["Namespaces"] = namespaces;
}
routes.Add(name, route);
return route;
}
}
public class clsRouteData : Route
{
public clsRouteData(string url, IRouteHandler routeHandler)
: base(url, routeHandler)
{
}
public override RouteData GetRouteData(HttpContextBase httpContext)
{
RouteData data = base.GetRouteData(httpContext);
if (data != null)
{
var SeoFriendliyName = data.Values["SeoFriendlyName"] as string;
if (SeoFriendliyName=="india-raj-jaipur")
{
data.Values["controller"] = "City";
data.Values["action"] = "Index";
// Can be send parameter
//data.Values["Id"] = Resutls.Id;
}
}
else
{
data.Values["controller"] = "Norecord";
data.Values["action"] = "Index";
// Can be send parameter
//data.Values["Id"] = Resutls.Id;
}
return data;
}
}

Controller for serving images doesn't work with extensions

I'd like to serve my images by using an ImageController:
public class ImageController : Controller
{
// GET: Image
public ActionResult Render(string fileName)
{
byte[] image = System.IO.File.ReadAllBytes(/*some path*/);
return this.Image(image, "image/png");
}
}
I added the route:
routes.MapRoute(
name: "Images",
url: "images/{action}/{fileName}",
defaults: new { controller = "Image", action = "Render", fileName = UrlParameter.Optional }
);
So this image path works:
http://xxx.xxx/images/render/x
But a path with this extension doesn't:
http://xxx.xxx/images/render/x.png
A "HTTP Error 404.0 - Not Found" error appears.
What should I do to enable file extensions?
Try following steps:
Enable custom file routing inside RouteConfig.cs
routes.RouteExistingFiles = true;
Add the following handler inside your web.config
<system.webServer>
<handlers>
<add name="ProtectedImages" path="images/*" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
</system.webServer>

Asp.net mvc routing - how to allow .html extension in mvc routing

Controller Name is : TestController
Action Name is :HtmlContent
and Url : localhost:53907/en_US/Index.html
I would like to call HtmlContent action from TestController if url which contains .html extension.
I have placed breakpoint in HtmlContent but its not hitting if i enter url like mentioned above,
routes.MapRoute(
name: "MyCustomRoute",
url: "en_US/{pagename}",
defaults: new { controller = "Test", action = "HtmlContent" },
constraints: new {pagename = #".*?$(?<=\.html)" }
);
How to write routing for this requirement?
routes.MapRoute(
name: "MyCustomRoute",
url: "en_US/{pagename}.html",
defaults: new { controller = "Test", action = "HtmlContent" },
constraints: new {pagename = #".*?$(?<=\.html)" }
);
and add code on web.config
<add name="HtmlFileHandler" path="*.html" verb="GET" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />
its work for me if any query .please comment

Resources