我是在web-api中构建一个测试应用程序,但我的返回对象没有被序列化
控制器
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Thoughts.Models;
using Newtonsoft.Json;
namespace Thoughts.Controllers
{
public class TagsController : Controller
{
//
// GET: /Tags/
public ActionResult Index()
{
return View();
}
public Message test(){
Message msg = new Message();
msg.Content = "jo";
return msg;
}
}
}
消息模型
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Thoughts.Models
{
[Serializable]
public class Message //: NamedObject
{
string content;
public string Content
{
get { return content; }
set { content = value; }
}
/*public NamedObject User;
public string timestamp;
public List<NamedObject> tags;
public Guid communityid;
public List<Message> comments;
public int commentCount;
public string parent;*/
}
}
路由器配置
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
namespace HelloWebAPI
{
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
}
}
WebApiConfig
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
namespace Thoughts
{
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
}
我的/ api网址也不起作用
答案 0 :(得分:1)
您需要从ApiController
继承Web API(Web API控制器与MVC控制器分开):
public class TagsController : ApiController {
[System.Web.Http.HttpGet]
public Message test(){
Message msg = new Message();
msg.Content = "jo";
return msg;
}
}
由于您的HTTP路由是api/{controller}/{action}/{id}
您现在可以调用它:/api/tags/test
最后,对于Web API,您不需要[Serializable]
属性。