【问题标题】:Cannot implicitly convert Web.Http.Results.JsonResult to Web.Mvc.JsonResult无法将 Web.Http.Results.JsonResult 隐式转换为 Web.Mvc.JsonResult
【发布时间】:2014-07-27 08:16:34
【问题描述】:

我已经在控制器上设置了这个测试方法,以消除它的任何复杂性。根据我从搜索中找到的所有结果,这应该可行。我不确定我在这里缺少什么。

public JsonResult test() 
{
    return Json(new { id = 1 });
}

这是我得到的错误。

无法将类型“System.Web.Http.Results.JsonResult”隐式转换为“System.Web.Mvc.JsonResult”

【问题讨论】:

  • 请注意直接问题与匿名类型无关。
  • Json(object data) 返回所需System.Web.Mvc.JsonResult 的方法是System.Web.Mvc.Controller受保护 方法。您需要从 Controller 类继承才能使用它。如果您的控制器继承自(例如)ApiController(在我的情况下;-)您正在使用返回System.Web.Http.Results.JsonResult<T>Json<T>(T content)方法...

标签: c# asp.net-mvc json asp.net-mvc-5 jsonresult


【解决方案1】:

你应该返回一个 JsonResult 而不仅仅是 Json

 public JsonResult test() 
    {
        var result = new JsonResult();
        result.Data = new
        {
             id = 1
         };
        result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
        return result;
    }

【讨论】:

    【解决方案2】:

    尝试以下方法:

    public System.Web.Http.Results.JsonResult test() 
    {
        return Json(new { id = 1 });
    }
    

    似乎Json 不会生成System.Web.Mvc.JsonResult,因为您可能是using System.Web.Mvc;,而是System.Web.Http.Results.JsonResult
    更通用的也应该工作:

    public ActionResult test() 
    {
        return Json(new { id = 1 });
    }
    

    注意:
    在我的 MVC 控制器中,Json 方法确实返回了System.Web.Mvc.JsonResult。您是从默认的System.Web.Mvc.Controller 继承的吗?

    【讨论】:

    • @ToanNguyen:是的,也不是。对我来说,初始代码正在运行,因为Json 在我的控制器中确实返回了System.Web.Mvc.JsonResult。但根据例外情况,他的情况并非如此......
    【解决方案3】:

    试试

    return Json(new { id = 1 }, JsonRequestBehavior.AllowGet);

    【讨论】:

      【解决方案4】:

      您需要通过模型类而不是匿名类返回数据。喜欢:

      public System.Web.Http.Results.JsonResult<modelClass> test(){
              return Json(new modelClass(){ id=1 });
      }
      

      【讨论】:

        【解决方案5】:

        在 MVC 中,JsonResult 继承自 ActionResult,而 ActionResult 位于命名空间 System.Web.Mvc

        这就是为什么你应该将System.Web.Mvc.JsonResult 引用为::

        public System.Web.Mvc.JsonResult test() 
        {
            return Json(new { id = 1 });
        }
        

        【讨论】:

          【解决方案6】:

          把这个放在你的使用中:

          using System.Web.Http.Results;
          

          然后你的行动:

          public JsonResult<YourClass> Get(string Search)
                  {
                     var Search = Search
                     return Json(Search);
                  }
          

          【讨论】:

            猜你喜欢
            • 2018-09-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2014-04-04
            • 1970-01-01
            • 2019-05-15
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多