在不嵌入的情况下直接从 URL 读取值时出现异常

Exception while reading value directly from the URL without embedding

在 ASP.NET MVC 4 项目中,我有一个简单的函数:

   public string chk(int tmp)
    {
          string message = "Stoe.Brose, Genre =" + tmp;
            return message;
    }

我从 url 获取 tmp 值作为:http://localhost:55142/store/chk/8

我没有在浏览器中显示值,而是 exception as :

    The parameters dictionary contains a null entry for parameter 'tmp' 
of non-nullable type 'System.Int32' for method 'System.String chk(Int32)'
 in 'MvcApplication3.Controllers.StoreController'. An optional parameter must
 be a reference type, a nullable type, or be declared as an optional parameter.

完整代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MvcApplication3.Controllers
{
    public class StoreController : Controller
    {
        public string chk(int tmp)
        {
              string message = "Stoe.Brose, Genre =" + tmp;
                return message;
        }
    }
}

在您的路由配置 (~/App_Start/RouteConfig.cs) 中,您有这一行:

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

这告诉路由系统从哪里提取参数。请注意,在操作之后,您告诉它 id,并告诉它这是一个可选参数。但是在您的控制器中,您期望 tmp。有四种解决方案:


将您的控制器更改为期望 id 而不是 tmp,并使 id 可为空。

public string chk(int? id)
{
    string message = "Stoe.Brose, Genre =" + id;
    return message;
}

更改路由以期望 tmp 并使 tmp 可为空。

routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{tmp}",
                defaults: new { controller = "Home", action = "Index", tmp = UrlParameter.Optional }
            );

public string chk(int? tmp)
   {
       string message = "Stoe.Brose, Genre =" + tmp;
       return message;
   }

或通过查询字符串

传递 tmp
/store/chk?tmp=5

并使其可为空。

public string chk(int? tmp)
{
    string message = "Stoe.Brose, Genre =" + tmp;
    return message;
}

你也可以使用attribute routing来告诉它如何映射参数。请注意,属性路由仅在 MVC 5 及更高版本中可用。

[Route("chk/{tmp}")]
public string chk(int? tmp)
    {
        string message = "Stoe.Brose, Genre =" + tmp;
        return message;
    }