簡體   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