【问题标题】:get specific URI working in asp.net mvc获取在 asp.net mvc 中工作的特定 URI
【发布时间】:2016-08-01 10:42:44
【问题描述】:

我的目标是让这些 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:

我认为这是相关的:

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

【问题讨论】:

  • 首先,尝试在 web.config 中添加:<modules runAllManagedModulesForAllRequests="true" /> <system.webServer> 部分,以允许带有文件扩展名的路由。
  • 您不使用路由中的默认值。试试看。还有一件事是你应该把它放在你的默认 MapRoute 的顶部,它路由到 HomeController/Index 。
  • @SlavaUtesinov - 在我的 web.config 中看不到 system.webServer。我错过了什么吗?
  • @csetzkorn,如果没有,请添加此部分。
  • 正如@MRebati 所说,您还没有在这里定义默认路由。所以至少定义一个默认动作,在这种情况下是“索引”。

标签: c# asp.net-mvc


【解决方案1】:

首先,您应该以这种方式修复您的 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>

附:您只能通过Index 操作处理对文件的请求。

【讨论】:

    【解决方案2】:

    开始使用App_Start/RouteConfig.cs中提供的Routes

    它有一些文档here:

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

    如果您想向用户发送一些文件,请尝试在控制器中执行操作以将其作为 ContentResult 发送给您。然后在 RouteConfig 中路由所有这些。

    【讨论】:

    • 对不起,这不起作用 - 我已经调整了我的原始要求,希望让事情更清楚。
    【解决方案3】:

    您可以在方法上添加路由配置:

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

    【讨论】:

      猜你喜欢
      • 2016-11-05
      • 2016-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多