Asp.net mvc 4 mvc4 web api中的嵌套类型,JSON来自AS3/FLEX,为空
解决了!检查柱子底部,寻找解决方案 因此,我有一个正在开发的web api,对于仅由基本类型组成的简单类型,Get和Post的工作都非常出色。一个有效的示例:Asp.net mvc 4 mvc4 web api中的嵌套类型,JSON来自AS3/FLEX,为空,asp.net-mvc-4,asp.net-web-api,entity-framework-5,Asp.net Mvc 4,Asp.net Web Api,Entity Framework 5,解决了!检查柱子底部,寻找解决方案 因此,我有一个正在开发的web api,对于仅由基本类型组成的简单类型,Get和Post的工作都非常出色。一个有效的示例: public class Investigator { public int InvestigatorId { get; set; } public string Name { get; set; } } 但是,对于嵌套类型,嵌套对象返回为其默认表示形式0,并根据类型返回空值。下面
public class Investigator
{
public int InvestigatorId { get; set; }
public string Name { get; set; }
}
但是,对于嵌套类型,嵌套对象返回为其默认表示形式0,并根据类型返回空值。下面是一个不起作用的示例:
public class Project
{
public int ProjectId { get; set; }
public string ProjectName { get; set; }
public virtual State State { get; set; }
public string City { get; set; }
public virtual Investigator ProjectInvestigator { get; set; }
}
当我调用uri发布项目时,除了嵌套类型之外,所有字段都正常运行,它们以默认表示形式返回,Investor返回时id为0,name为null。如果我没有在post请求中包含调查员,调查员对象本身将作为null而不是默认对象。所以我知道它至少被代码看到了,但是它没有正确地反序列化或者其他什么。这可能是什么原因造成的?在反序列化之前,我可以在哪里查看传入的数据
其他可能相关的代码部分是控制器:
public class ProjectsController : ApiController
{
private NovascotiaContext db = new NovascotiaContext();
protected override void Initialize(System.Web.Http.Controllers.HttpControllerContext controllerContext)
{
base.Initialize(controllerContext);
db.Configuration.ProxyCreationEnabled = false;
}
// GET api/Projects
public IEnumerable<Project> GetProjects()
{
return db.Projects.AsEnumerable();
}
// GET api/Projects/5
public Project GetProject(int id)
{
Project project = db.Projects.Find(id);
if (project == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return project;
}
// PUT api/Projects/5
public HttpResponseMessage PutProject(int id, Project project)
{
if (!ModelState.IsValid)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
if (id != project.ProjectId)
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
db.Entry(project).State = EntityState.Modified;
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK);
}
// POST api/Projects
public HttpResponseMessage PostProject([FromBody]Project project)
{
if (ModelState.IsValid)
{
db.Projects.Add(project);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, project);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = project.ProjectId }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
// DELETE api/Projects/5
public HttpResponseMessage DeleteProject(int id)
{
Project project = db.Projects.Find(id);
if (project == null)
{
return Request.CreateResponse(HttpStatusCode.NotFound);
}
db.Projects.Remove(project);
try
{
db.SaveChanges();
}
catch (DbUpdateConcurrencyException ex)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, ex);
}
return Request.CreateResponse(HttpStatusCode.OK, project);
}
protected override void Dispose(bool disposing)
{
db.Dispose();
base.Dispose(disposing);
}
}
其中projectPostService是一个方法为POST的HTTPService对象。奇怪的是,在写这篇文章的时候,我创建了一个简单的页面来访问服务,结果很好,这显然是as3/flex和web api之间的通信。以下是有效的页面:
你能分享你的原始“帖子”请求吗?
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
// Uncomment the following line of code to enable query support for actions with an IQueryable or IQueryable<T> return type.
// To avoid processing unexpected or malicious queries, use the validation settings on QueryableAttribute to validate incoming queries.
// For more information, visit http://go.microsoft.com/fwlink/?LinkId=279712.
//config.EnableQuerySupport();
// To disable tracing in your application, please comment out or remove the following line of code
// For more information, refer to: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing();
}
}
var p:Project = new Project();
p.City = "ACity";
p.ProjectName = "AProjectName";
var state:data.State = new data.State();
state.StateId = 98;
state.StateName = "Tennessee";
p.State = state;
var investigator:Investigator = new Investigator();
investigator.InvestigatorId = 1;
investigator.Name = "John Doe";
p.ProjectInvestigator = investigator;
projectPostService.send(p);
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
<script src="Scripts/jquery-1.8.2.js"></script>
<script type="text/javascript">
$(document).ready(function () {
alert("ready");
var project = {
"ProjectId": 2,
"ProjectName": "Aprojectname",
"State": { "StateId": 98, "StateName": "Tennessee" },
"ProjectInvestigator": { "InvestigatorId": 1, "Name": "John Doe" }
};
$.ajax({
url: "http://localhost/api/Projects",
type: 'POST',
dataType: 'json',
data: project,
success: function (data) {
alert(JSON.stringify(data));
},
failure: function (data) {
alert('fail');
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
</div>
</form>
</body>
</html>
var p:Project = new Project();
p.City = "ACity";
p.ProjectName = "AProjectName";
var state:data.State = new data.State();
state.StateId = 98;
state.StateName = "Tennessee";
p.State = state;
var investigator:Investigator = new Investigator();
investigator.InvestigatorId = 1;
investigator.Name = "John Doe";
p.ProjectInvestigator = investigator;
var loader:URLLoader = new URLLoader();
var hdr:URLRequestHeader = new URLRequestHeader("Content-Type", "application/json");
var request:URLRequest = new URLRequest("http://localhost/api/Projects");
request.requestHeaders.push(hdr);
request.data = com.adobe.serialization.json.JSON.encode(p);
request.contentType = "TEXT";
request.method = "POST";
loader.addEventListener(Event.COMPLETE, function(e:Event):void{
trace(loader.data); //return
});
loader.load(request);