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

时间:2015-01-28 15:47:14

标签: asp.net-mvc

在ASP.NET MVC 4项目中,我有简单的功能:

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

我从网址获取tmp值为:http://localhost:55142/store/chk/8

我没有获得浏览器中显示的值,而是将异常视为:

    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;
        }
    }
}

1 个答案:

答案 0 :(得分:1)

在你的路线配置(~/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;
    }