c# - Web Api Controller 中无法识别 Json 方法

标签 c# .net json asp.net-mvc asp.net-web-api

我有一个 web api Controller

using sport.BLL.Abstract;
using sport.BLL.Concrete;
using sport.DAL.Entities;
using sport.webApi.Models;
using AutoMapper;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;  
using Microsoft.Owin.Security;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web;
using System.Web.WebPages.Html;

namespace sport.webApi.Controllers 
{
    public class AccountManageController : ApiController
    {
        [HttpPost]
        public System.Web.Mvc.ActionResult CreateAccount(CollaborateurModel item)
        {
            var user = new ApplicationUser { UserName = item.Username, Email = item.Email };
            var result = UserManager.CreateAsync(user, item.Password);
            if (result.Result.Succeeded)
            {

                var currentUser = UserManager.FindByName(item.Username);
                var roleresult = UserManager.AddToRole(currentUser.Id, item.Role);
                ajt_collaborator entity = Mapper.Map<CollaborateurModel, ajt_collaborator>(item);
                entity.id_user_fk = currentUser.Id;
                entity.is_deleted = false; 
                repo.CreateCollaborator(entity); 
                var response = new { Success = true }; 
                return  Json(response);


            }
            else
            {
                var errorResponse = new { Success = false, ErrorMessage = "error" };
                return  Json(errorResponse);
            }

        }
    }
}

我在这一行中遇到错误:

返回Json(响应);

无法识别 Json 方法!!!当我用谷歌搜索时,我得到了这个 link这表明 Json 方法包含在 System.Web.Mvc 中。即使我尝试导入此命名空间,我也会遇到同样的错误?

  1. 那么这个错误的原因是什么?
  2. 我该如何解决?

最佳答案

问题是您继承自ApiController,但JsonSystem.Web.Mvc.Controller 的成员。

尝试使用 JsonResult:

return new JsonResult { data = yourData; }

您可以将任何对象设置为数据,因为它将被序列化为 JSON。

比如你只需要返回一个操作的结果,你可以这样使用:

return new JsonResult { data = true; } // or false

但是,描述结果类和返回对象是一个很好的做法。

关于c# - Web Api Controller 中无法识别 Json 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30726242/

相关文章:

c# - DataGridView:复制完整到剪贴板

javascript - 从 json 对象中删除特定项目

java - Gson gson = new Gson().toJson(data) - 不兼容的类型

c# - 无法在 C# 中加载 DLL 'tesseract.dll'

c# - 未调用 DataTemplate 中的命令

c# - Unity3d - 如何有效地从属于另一个游戏对象的另一个类调用方法

c# - Control.Invoke() 和 Control.BeginInvoke() - 过去的参数存储在哪里?它是如何处置的?

json - 如何在 Swift 中格式化 JSON 字符串?

c# - 无法连接到 Web 服务

c# - 将整数转换为字节