cs0815
cs0815

Reputation: 17428

get specific URI working in asp.net mvc

I aim to get these URIs to work in ASP.NET MVC:

http://localhost:57165/Blas/bla1.xml
http://localhost:57165/Blas/bla2.xml
...
http://localhost:57165/Blas/blan.xml

As you can see the file name can vary and the controller action is ultimately meant to spew out xml file given the file name.

I have this controller:

public class BlasController : Controller
{
    // GET: SiteMaps
    public ActionResult Index(string fileName)
    {
        return View();
    }
}

and this routing code:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapRoute(
            "Blas",
            "{controller}/{fileName}"
          );
}

Unfortunately, I get a 404. Is it possible to get this to work?

PS:

I think this is related:

Create a MVC route ending ".js" and returning JavaScript?

Upvotes: 0

Views: 103

Answers (3)

AdrienTorris
AdrienTorris

Reputation: 9391

You can add route config on the method :

[Route("Blas")]
public class BlasController : Controller
{
    [HttpGet("{fileName}")]
    public ActionResult Index(string fileName)
    {
        return View();
    }
}

Upvotes: 0

Slava Utesinov
Slava Utesinov

Reputation: 13498

First, you should fix your RegisterRoutes method this way:

public static void RegisterRoutes(RouteCollection routes)
{
    routes.MapRoute(
        name: "FileRoute",
        url: "{controller}/{fileName}",
        defaults: new { action = "Index" },
        constraints: new { fileName = @"^[\w\-. ]+$" }
    );

    routes.MapRoute(
        name: "Default",
        url: "{controller}/{action}/{id}",
        defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
    );
}

Second, add this rows to web.config:

<system.webServer>
    <modules runAllManagedModulesForAllRequests="true" /> 
</system.webServer>

P.S. You can process requests to files only at Index action.

Upvotes: 1

MRebati
MRebati

Reputation: 599

Start using Routes which is available in App_Start/RouteConfig.cs

it has some documentation here:

//This is Static Route.
routes.MapRoute(
        name: "BlaBla",
        url: "/Blas/bla.txt",
        defaults: new { controller = "YourController", action = "YourAction" }
    );

if you want to send some file to user try an action in controller to send it as ContentResult for you. then Route all of them in RouteConfig.

Upvotes: 0

Related Questions