【问题标题】:Is it possible to define a parameter before action in url是否可以在 url 中的操作之前定义参数
【发布时间】:2016-03-21 11:32:28
【问题描述】:

问题就像标题一样简单。

是否可以有如下所示的路由:{controller}/{id}/{action}

这就是我现在的代码(只是一个简单的函数)(device 是我的控制器):

[HttpGet]
[Route("Device/{id}/IsValid")]
public bool IsValid(int id) {
    return true;
}

但是当我转到以下 URL 时,浏览器说找不到该页面:localhost/device/2/IsValid

当我尝试这个 URL 时,它工作得很好:localhost/device/IsValid/2

那么,是否可以使用localhost/device/2/IsValid 代替默认路由localhost/device/IsValid/2?以及如何做到这一点?

欢迎询问更多信息!提前致谢!

【问题讨论】:

  • 您需要更改RouteConfig文件中的代码。 public static void RegisterRoutes(RouteCollection routes) { routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); routes.MapRoute( "Default", // 路由名称 "{controller}/{id}/{action}", // 带参数的 URL new { controller = "Home", action = "Index", id = "" } // 参数默认值 ); }
  • @RahulChavan th 是什么?我必须在哪里添加它?
  • App_start 中的RouteConfig文件
  • 这是用于 web api 还是普通 mvc
  • 也可以用于WebAPI

标签: c# asp.net-mvc asp.net-mvc-routing


【解决方案1】:

您正在使用属性路由。确保启用属性路由。

Attribute Routing in ASP.NET MVC 5

对于 MVC RouteConfig.cs

public class RouteConfig {

    public static void RegisterRoutes(RouteCollection routes) {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapMvcAttributeRoutes();

        //...Other code removed for brevity
    }
}

在控制器中

[RoutePrefix("device")]
public class DeviceController : Controller {
    //GET device/2/isvalid
    [HttpGet]
    [Route("{id:int}/IsValid")]
    public bool IsValid(int id) {
        return true;
    }
}

【讨论】:

  • 感谢您的帮助! :D 但是,为什么是“:int”?我为什么要这样做?
  • 它是基于您的样本的约束。它可以很容易地成为boollong。如果您想确保 url 中使用的类型符合您想要的类型。你不必这样做。阅读参考文章。
【解决方案2】:

尝试在DefaultRoutingConfig 中的路由之前使用它

config.Routes.MapHttpRoute(
    "RouteName",
    "{controller}/{id}/{action}"
    );

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    相关资源
    最近更新 更多