繁体   English   中英

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

[英]get specific URI working 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

如您所见,文件名可能会有所不同,并且控制器操作最终旨在根据给定的文件名弹出xml文件。

我有这个控制器:

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

和此路由代码:

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

不幸的是,我得到了404。能否使其正常工作?

PS:

我认为这是相关的:

创建以“ .js”结尾并返回JavaScript的MVC路由?

首先,您应该通过以下方式修复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 }
    );
}

其次,将此行添加到web.config中:

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

PS您只能在“ Index操作中处理对文件的请求。

开始使用App_Start/RouteConfig.cs可用的路由

在这里有一些文档:

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

如果要向用户发送文件,请尝试在控制器中执行一项操作,以将其作为ContentResult发送给您。 然后将它们全部路由到RouteConfig中。

您可以在方法上添加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