简体   繁体   English

获取在asp.net mvc中工作的特定URI

[英]get specific URI working in asp.net mvc

I aim to get these URIs to work in ASP.NET MVC: 我旨在使这些URI在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. 如您所见,文件名可能会有所不同,并且控制器操作最终旨在根据给定的文件名弹出xml文件。

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? 不幸的是,我得到了404。能否使其正常工作?

PS: PS:

I think this is related: 我认为这是相关的:

Create a MVC route ending ".js" and returning JavaScript? 创建以“ .js”结尾并返回JavaScript的MVC路由?

First, you should fix your RegisterRoutes method this way: 首先,您应该通过以下方式修复RegisterRoutes方法:

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: 其次,将此行添加到web.config中:

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

PS You can process requests to files only at Index action. PS您只能在“ Index操作中处理对文件的请求。

Start using Routes which is available in App_Start/RouteConfig.cs 开始使用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. 如果要向用户发送文件,请尝试在控制器中执行一项操作,以将其作为ContentResult发送给您。 then Route all of them in RouteConfig. 然后将它们全部路由到RouteConfig中。

You can add route config on the method : 您可以在方法上添加route config:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM