C# 是否可以使用路由URL段而不是查询字符串将空字符串传递给操作方法?

C# 是否可以使用路由URL段而不是查询字符串将空字符串传递给操作方法?,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我有一个控制器类Movie。其作用方式之一如下: public string ActionMethod(string id) { if (id == null) { return "null"; } if (id == string.Empty) { return "empty"; } return "neith

我有一个控制器类
Movie
。其作用方式之一如下:

    public string ActionMethod(string id)
    {

        if (id == null)
        {

            return "null";
        }

        if (id == string.Empty)
        {

            return "empty";
        }

        return "neither null nor empaty";
    }
是否可以使用路由URL段而不是查询字符串将空字符串传递给操作方法


请注意
http://localhost:21068/Movies/ActionMethod?id=
可以这样做,但它使用查询字符串。此外,不允许修改操作方法。:-)

如果您的ID为空,请不要传递任何查询字符串。像

    http://localhost:21068/Movies/ActionMethod

我不清楚您想要实现什么,但您可以通过在Global.asax.cs中适当地指定路由来实现。作为一个人为的例子,如下所示:

routes.MapRoute(
    "", 
    "{controller}/{action}/id/{id}", 
    new { controller = "Home", action = "Index", id = "" } 
    );

routes.MapRoute(
    "Default", 
    "{controller}/{action}/{id}", 
    new { controller = "Home", action = "Index", id = UrlParameter.Optional }             
    );
允许您使用:

http://localhost:21068/Movies/ActionMethod        - id is null
http://localhost:21068/Movies/ActionMethod/id/    - id is an empty string
http://localhost:21068/Movies/ActionMethod/id/123 - id is a nonempty string

如果您声明希望允许哪些URL以及如何映射它们,毫无疑问会有人建议您如何设置路由。

如果您不能使用查询字符串,您是否考虑过使用表单?我还没有测试过,但试一试:

@using (Html.BeginForm("ActionMethod", "YourControllerName", "GET")) {
    <input type="text" name="id">
    <input type="submit" name="submitForm" value="submitForm" />
  }
@使用(Html.BeginForm(“ActionMethod”、“YourControllerName”、“GET”)){
}

参考:

我认为您可以传递可为null的参数,如:

public string ActionMethod(string? id)
然后,不传递任何查询字符串作为:

http://localhost:21068/Movies/ActionMethod

传递一个特殊的字符序列或添加一个新参数,该参数将指示
ActionMethod
包含字符串。Empty@JesseJames当前位置请用代码显示,我看不懂。很抱歉,您正在接受HTTP/HTML的馈送,这些HTTP/HTML实际上没有空和空的不同概念。所以你不应该想要这个。string不是一个值类型,也不能为null。Lolz-yeh,在看到我的这个答案后,我想:-O我说了吗?