将 Json 回传数据转换为 XML
Posted
技术标签:
【中文标题】将 Json 回传数据转换为 XML【英文标题】:Converting Json Post Back Data To XML 【发布时间】:2019-05-31 05:22:33 【问题描述】:这是我的第一个网络应用项目。我正在为我的视图模型使用 VS 社区、asp.net、bootstrap 4、C# 和 JS 淘汰赛,服务器端数据来自使用实体框架的公司 ERP SQL 数据库。
这个想法是,用户从公司 ERP 系统中接收要批准的项目列表,这些项目被加载到视图模型中。 View Model 的结构是一个 JS Knockout observable 数组,每个项目都是一个 JS 淘汰项目 observables(见下面的完整代码)
一旦用户根据需要处理了项目,我希望 Web 应用程序将整个 View Modal 作为 Json 对象回发,并让服务器 Post Controller 将此 Json 对象转换为 xml 以发送到存储的 SQL插入SQL数据库的过程,从SQL数据库处理数据并插入到ERP数据库中
当我尝试操作帖子时,我收到 405“不允许的方法”
> "tags":
"ai.cloud.roleInstance": "[MYCOMPUTER].local",
"ai.operation.id": "c07680cd8c845240a9e3791018c39521",
"ai.operation.name": "POST ReqsTests",
"ai.location.ip": "::1",
"ai.internal.sdkVersion": "web:2.8.0-241",
"ai.internal.nodeName": "[MYCOMPUTER].local"
,
"data":
"baseType": "RequestData",
"baseData":
"ver": 2,
"id": "|c07680cd8c845240a9e3791018c39521.66f8d951_",
"name": "POST ReqsTests",
"duration": "00:00:00.0279394",
"success": false,
"responseCode": "405",
"url": "http://localhost:64234/api/ReqsTests/",
"properties":
"DeveloperMode": "true",
"_MS.ProcessedByMetricExtractors": "(Name:'Requests', Ver:'1.1')"
我认为我没有正确收到来自客户端的 Json 日期。我的想法是因为我将整个模型发回,这是一个 Json 列表,但我的控制器不接收列表而是字符串。
谁能解释我的控制器应该如何接收客户端数据 这是我从客户端和服务器 Post 控制器对我的控制器的调用,下面是完整的代码清单
self.postAllReqs = function(self)
self.error(''); // Clear error message
var data = ko.toJSON(self.Reqs); // convert to json
console.log(data);
ajaxHelper(reqsUri, 'POST', data).fail(function (jqXHR, textStatus, errorThrown)
self.error(errorThrown);
);
// POST: api/ReqsTests
public IHttpActionResult PostReqsTest(string json)
if (!ModelState.IsValid)
return BadRequest(ModelState);
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);
try
//SQL store procedure
SqlParameter param1 = new SqlParameter("@XmlIn", doc);
db.Database.ExecuteSqlCommand("exec [CHC_Web].[TestWebHandShake],@XmlIn",
param1);
catch (Exception e)
string message = e.Message;
return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message));
return Ok();
谢谢
查看型号代码
function ReqsTest(rt)
rt = rt || ;
var self = this;
self.id = ko.observable(rt.ID || 0);
self.requisition = ko.observable(rt.Requisition || "");
self.reqnStatus = ko.observable(rt.ReqnStatus || "");
self.dateReqnRaised = ko.observable(rt.DateReqnRaised|| null);
self.reqnValue = ko.observable(rt.ReqnValue || null);
self.approvedValue = ko.observable(rt.ApprovedValue || null);
self.originator = ko.observable(rt.Originator || "");
self.origName = ko.observable(rt.OrigName || "");
self.origEmail = ko.observable(rt.OrigEmail || "");
self.line = ko.observable(rt.Line || 0.00);
self.indx = ko.observable(rt.INDX || 0);
self.dateReqnRaisedL = ko.observable(rt.DateReqnRaisedL || null);
self.reqStatus = ko.observable(rt.ReqStatus || "");
//self.reqBackground = ko.observable(rt.ReqBackground || "");
//Computed observables
self.reqBackground = ko.computed(function ()
// get variable
var status = self.reqStatus();
if (status == "A") return "card-heading bg-success text-white";
else if (status == "D") return "card heading bg-secondary";
else if (status == "R") return "card heading bg-warning";
else if (status == "E") return "card heading bg-danger";
else
return "card-heading bg-primary text-white";
)
self.reqStatusLabel = ko.computed(function ()
// get variable
var status = self.reqStatus();
if (status == "A") return "Approved";
else if (status == "D") return "Declined - put on hold";
else if (status == "R") return "Routing On";
else if (status == "E") return "Erase On Syspro";
else
return "Awaiting Approval";
)
self.approvalBtn = ko.computed(function ()
// get variable
var status = self.reqStatus();
if (status == "A") return "css: button btn-secondary ";
else
return "btn btn-success ";
)
self.approvalBtnLbl = ko.computed(function ()
// get variable
var status = self.reqStatus();
if (status == "W") return "Approve";
else
return "UnApprove";
)
self.declineBtnLbl = ko.computed(function ()
// get variable
var status = self.reqStatus();
if (status == "D") return "UnDecline";
else
return "Decline";
)
self.deleteBtnLbl = ko.computed(function ()
// get variable
var status = self.reqStatus();
if (status == "E") return "Restore";
else
return "Erase";
)
// Functions
//show details alert
$(".btn").on("click", function ()
$(".alert").removeClass("in").show();
$(".alert").delay(200).addClass("in").fadeOut(2000);
);
function ReqsViewModel ()
var self = this;
self.Reqs = ko.observableArray([]);
self.error = ko.observable();
var reqsUri = '/api/ReqsTests/';
function ajaxHelper(uri, method, data)
self.error(''); // Clear error message
return $.ajax(
type: method,
url: uri,
dataType: 'json',
contentType: 'application/json',
data: data ? JSON.stringify(data) : null
).fail(function (jqXHR, textStatus, errorThrown)
self.error(errorThrown);
);
function getAllReqs()
ajaxHelper(reqsUri, 'GET').done(function (data)
// Build the ReqsTest objects
var reqs = ko.utils.arrayMap(data, function (rt)
return new ReqsTest(rt);
);
self.Reqs(reqs);
);
self.postAllReqs = function(self)
self.error(''); // Clear error message
var data = ko.toJSON(self.Reqs); // convert to json
console.log(data);
ajaxHelper(reqsUri, 'POST', data).fail(function (jqXHR, textStatus, errorThrown)
self.error(errorThrown);
);
// Details
self.detail = ko.observable();
self.getReqDetail = function (item)
//var url = reqsUri + item.indx();
//ajaxHelper(url, 'GET').done(function (data)
// self.detail(data);
//
//);
self.detail(item)
//Approval function
self.Approval = function (item)
var status = item.reqStatus();
if (status == "W") item.reqStatus("A");
else
item.reqStatus("W");
self.getReqDetail(item);
//Decline function
self.Decline = function (item)
var status = item.reqStatus();
if (status == "D") item.reqStatus("W");
else item.reqStatus("D");
self.getReqDetail(item);
//Delete function
self.Delete = function (item)
var status = item.reqStatus();
if (status == "E") item.reqStatus("W");
else item.reqStatus("E");
self.getReqDetail(item);
// Load the reqs - Take this out if you don't want it
getAllReqs();
ko.applyBindings(new ReqsViewModel());
模型类
namespace POC_Reqs_v1.Models
using System;
using System.Collections.Generic;
public partial class ReqsTest
public string ID get; set;
public string Requisition get; set;
public string ReqnStatus get; set;
public Nullable<System.DateTime> DateReqnRaised get; set;
public Nullable<decimal> ReqnValue get; set;
public Nullable<decimal> ApprovedValue get; set;
public string Originator get; set;
public string OrigName get; set;
public string OrigEmail get; set;
public decimal Line get; set;
public long INDX get; set;
public string DateReqnRaisedL get; set;
public string ReqStatus get; set;
public string ReqBackground get; set;
控制器代码
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml;
using Newtonsoft.Json;
using POC_Reqs_v1.Models;
namespace POC_Reqs_v1.Controllers
public class ReqsTestsController : ApiController
private ChamberlinWebEntities db = new ChamberlinWebEntities();
// GET: api/ReqsTests
public IQueryable<ReqsTest> GetReqsTests()
return db.ReqsTests;
// GET: api/ReqsTests/5
[ResponseType(typeof(ReqsTest))]
public async Task<IHttpActionResult> GetReqsTest(string id)
var ID = Convert.ToInt64(id);
ReqsTest reqsTest = await db.ReqsTests.FindAsync(ID);
if (reqsTest == null)
return NotFound();
return Ok(reqsTest);
// PUT: api/ReqsTests/5
[ResponseType(typeof(void))]
public async Task<IHttpActionResult> PutReqsTest(string id, ReqsTest reqsTest)
if (!ModelState.IsValid)
return BadRequest(ModelState);
if (id != reqsTest.ID)
return BadRequest();
db.Entry(reqsTest).State = EntityState.Modified;
try
await db.SaveChangesAsync();
catch (DbUpdateConcurrencyException)
if (!ReqsTestExists(id))
return NotFound();
else
throw;
return StatusCode(HttpStatusCode.NoContent);
// POST: api/ReqsTests
public IHttpActionResult PostReqsTest(string json)
if (!ModelState.IsValid)
return BadRequest(ModelState);
XmlDocument doc = JsonConvert.DeserializeXmlNode(json);
try
//SQL store procedure
SqlParameter param1 = new SqlParameter("@XmlIn", doc);
db.Database.ExecuteSqlCommand("exec [CHC_Web].[TestWebHandShake],@XmlIn",
param1);
catch (Exception e)
string message = e.Message;
return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message));
return Ok();
// DELETE: api/ReqsTests/5
[ResponseType(typeof(ReqsTest))]
public async Task<IHttpActionResult> DeleteReqsTest(string id)
ReqsTest reqsTest = await db.ReqsTests.FindAsync(id);
if (reqsTest == null)
return NotFound();
db.ReqsTests.Remove(reqsTest);
await db.SaveChangesAsync();
return Ok(reqsTest);
protected override void Dispose(bool disposing)
if (disposing)
db.Dispose();
base.Dispose(disposing);
private bool ReqsTestExists(string id)
return db.ReqsTests.Count(e => e.ID == id) > 0;
【问题讨论】:
控制器代码应该只是任务完成的返回状态。不是 XML 数据。 XML 数据应该直接进入数据库。 您好,请给我一个返回状态语法的例子 见 msdn:docs.microsoft.com/en-us/aspnet/web-api/overview/… 和 ***.com/questions/21758615/… 【参考方案1】:为了完整起见,这是我的最终解决方案: 主要问题是post控制器中的语法错误,编译时没有产生错误,不正确的行是
// POST: api/ReqsTests
public IHttpActionResult PostReqsTest(string json)
最后是正确的语法
public async Task<IHttpActionResult> PostReqsTest(object json)
所以完整的控制器代码是
// POST: api/ReqsTests
public async Task<IHttpActionResult> PostReqsTest(object json)
if (!ModelState.IsValid)
return BadRequest(ModelState);
//convert the Json model to xml
XmlDocument doc = JsonConvert.DeserializeXmlNode(json.ToString());
try
//SQL store procedure
SqlParameter param1 = new SqlParameter("@XmlIn", doc.InnerXml);
db.Database.ExecuteSqlCommand("exec [CHC_Web].[TestWebHandShake] @XmlIn",
param1);
catch (Exception e)
string message = e.Message;
return ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, message));
return ResponseMessage(Request.CreateResponse HttpStatusCode.OK,"Inserted to database"));
【讨论】:
我想最后一行代码不应该是 CreateErrorResponse(HttpStatusCode.OK) 因为它不是错误?以上是关于将 Json 回传数据转换为 XML的主要内容,如果未能解决你的问题,请参考以下文章