Web Api控制器无法识别Json方法

Lam*_*fif 6 .net c# asp.net-mvc json asp.net-web-api

我有一个web api控制器

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

        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我在这行中遇到错误:

返回Json(回应);

Json方法无法识别!!! 当我用Google搜索时,我得到了这个链接,表明该Json方法已包含在内System.Web.Mvc.即使我尝试导入此命名空间,我得到相同的错误?

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

Yuv*_*kov 6

我该如何解决?

原因在于你不是继承Controller而是从ApiController前者Json(object o)作为基类中的方法继承,但这实际上并不重要,因为你的方法存在根本问题.

ApiController与WebAPI一起使用并不意味着返回一个ActionResult属于MVC的概念.相反,您只需返回POCO并让WebAPI框架为您处理序列化:

public object CreateAccount(CollaborateurModel item)
{
    // Do stuff:
    if (result.Result.Succeeded)
    {
        return new { Success = true }
    }
    else
    {
        return new { Success = false, ErrorMessage = "error" };   
    }                               
}
Run Code Online (Sandbox Code Playgroud)

您可以在文件中设置格式化程序配置Global.asax.cs,并准确告诉它使用哪些(在您的情况下,您需要JsonMediaTypeFormatter).


Yel*_*yev 6

问题是你继承自ApiController但是Json是其成员System.Web.Mvc.Controller.

尝试使用JsonResult:

return new JsonResult { data = yourData; }
Run Code Online (Sandbox Code Playgroud)

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

例如,如果您只需要返回操作结果,则可以这样使用它:

return new JsonResult { data = true; } // or false
Run Code Online (Sandbox Code Playgroud)

但是,描述结果类和返回对象是一种好习惯.