第三者が送信するデータに基づいて私の最初のWEB-APIサービスを作成しています。以下は、彼らが送信されますレイアウトです:私は、受注コードが各テーブルに共通している以下の4つのテーブル(受注、借り手、連絡先、プロパティ)でデータベースを作成したWEB APIエンティティ - フレームワーク親データベースの親子チャイルド
<StandardTitleOrderRequest>
<Authentication>
<UserName>{$USERNAME}</UserName>
<Password>{$PASSWORD}</Password>
</Authentication>
<Borrowers>
<Borrower>
<FirstName>{$BORROWER_FIRST_NAME}</FirstName>
<MiddleName>{$BORROWER_MIDDLE_NAME}</MiddleName>
<LastName>{$BORROWER_LAST_NAME}</LastName>
<SSN>{$BORROWER_SSN}</SSN>
</Borrower>
</Borrowers>-
<Property>
<Address>{$SUBJECT_ADDRESS_STREET}</Address>
<City>{$SUBJECT_ADDRESS_CITY}</City>
<State>{$SUBJECT_ADDRESS_STATE}</State>
<Zip>{$SUBJECT_ADDRESS_ZIP}</Zip>
<County>{$SUBJECT_ADDRESS_COUNTY}</County>
</Property>-
<Contact>
<Name>{$CONTACT_NAME}</Name>
<Phone>{$CONTACT_PHONE}</Phone>
<Fax>{$CONTACT_FAX}</Fax>
<Email>{$CONTACT_EMAIL}</Email>
</Contact>-
<OrderInfo>
<LoanNumber>{$LOAN_NUMBER}</LoanNumber>
<LoanAmount>{$LOAN_AMOUNT}</LoanAmount>
<ToBeInsured/>
<FileNumber>{$FileID}</FileNumber>
<OrderId>{$ORDER_ID}</OrderId >
<CostCenter>{$BRANCH_NAME}</CostCenter>
<Product>{$PRODUCT_NUMBER}</Product>
<Notes>{$ORDER_NOTES}</Notes>
<ResponseURL>{$RESPONSE_URL}</ResponseURL>
<PID></PID>
<PayOffLoanNumber></PayOffLoanNumber>
<ClientCode>{$CLIENT_ID}</ClientCode>
</OrderInfo>
を。注文には複数の借り手と1つの連絡先と1つの財産があります。私は(Fiddlerを使用して)注文や連絡先、借り手やプロパティを取得/ POST/PUT/DELETEできるようになる基本的なWeb APIを構築しました。注文を掲示し、その注文(借り手、連絡先、財産)の各子要素を投稿するロジックを追加する方法がわかりません。私はVS 2017とEF 6を使用しています。
私はお互いを参照するテーブルに外部キーを追加してからデータモデルを更新する必要があると仮定していますが、さまざまなエラーが発生します。
第三者は一度に1件の取引を掲載するため、入金データは一括ではなく、XMLとして送信されます。
私はWeb APIサービス全体でさまざまなチュートリアルを見てみましたが、90%は単一のPOSTを扱っています。実際には、XMLデータの受信と親と1人以上の子供への投稿に関する具体的な詳細はありません。さらに、私のアプリは現在、着信データをJSON形式でのみ受け付けます。以下は、いくつかの方向を探しているデータベースへのポストのための基礎となるはOrdersController(POST https://localhost:xxxx/api/Orders)amのコードがある
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using OrdersDataAccess;
namespace waEtitle.Controllers
{
public class OrdersController : ApiController
{
/// <summary>
/// Get Order Information
/// </summary>
/// <returns></returns>
///
public IEnumerable<Order> Get()
{
using (FirstCloseEntities entities = new FirstCloseEntities())
{
return entities.Orders.ToList();
}
}
public HttpResponseMessage Get(int id)
{
using (FirstCloseEntities entities = new FirstCloseEntities())
{
var entity = entities.Orders.FirstOrDefault(o => o.OrderID == id);
if (entity != null)
{
return Request.CreateResponse(HttpStatusCode.OK, entity);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Order with id = " + id.ToString() + " not found.");
}
}
}
public HttpResponseMessage Post([FromBody] Order order)
{
try
{
using (FirstCloseEntities entities = new FirstCloseEntities())
{
entities.Orders.Add(order);
entities.SaveChanges();
var message = Request.CreateResponse(HttpStatusCode.Created, order);
message.Headers.Location = new Uri(Request.RequestUri + order.OrderID.ToString());
return message;
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
public HttpResponseMessage Delete(int ID)
{
try
{
using (FirstCloseEntities entities = new FirstCloseEntities())
{
var entity = entities.Orders.FirstOrDefault(c => c.OrderID == ID);
if (entity == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Order with ID = " + ID.ToString() + " not found to delete.");
}
else
{
entities.Orders.Remove(entity);
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK);
}
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
public HttpResponseMessage Put(int id, [FromBody]Order order)
{
try
{
using (FirstCloseEntities entities = new FirstCloseEntities())
{
var entity = entities.Orders.FirstOrDefault(c => c.OrderID== id);
if (entity == null)
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Order with Id = " + id.ToString() + " not found to update.");
}
else
{
entity.LoanNumber = order.LoanNumber;
entity.LoanAmount = order.LoanAmount;
entity.ToBeInsured = order.ToBeInsured;
entity.FileNumber = order.FileNumber;
entity.CostCenter = order.CostCenter;
entity.Product = order.Product;
entity.Notes = order.Notes;
entity.ResponseURL = order.ResponseURL;
entity.PID = order.PID;
entity.PayOffLoanNumber = order.PayOffLoanNumber;
entity.ClientCode = order.ClientCode;
entities.SaveChanges();
return Request.CreateResponse(HttpStatusCode.OK, entity);
}
}
}
catch (Exception ex)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ex);
}
}
}
}
テーブル:現在
/* ==Scripting Parameters==
Source Server Version : SQL Server 2008 R2 (10.50.1617)
Source Database Engine Edition : Microsoft SQL Server Enterprise Edition
Source Database Engine Type : Standalone SQL Server
Target Server Version : SQL Server 2017
Target Database Engine Edition : Microsoft SQL Server Standard Edition
Target Database Engine Type : Standalone SQL Server
*/
USE [FirstCloseAPI]
GO
/****** Object: Table [dbo].[Borrowers] Script Date: 9/26/2017 1:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Borrowers](
[borID] [int] IDENTITY(1,1) NOT NULL,
[OrderID] [int] NULL,
[FirstName] [varchar](max) NULL,
[MiddleName] [varchar](max) NULL,
[LastName] [varchar](max) NULL,
[SSN] [varchar](max) NULL,
CONSTRAINT [PK_Borrowers] PRIMARY KEY CLUSTERED
(
[borID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[Contacts] Script Date: 9/26/2017 1:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Contacts](
[conId] [int] IDENTITY(1,1) NOT NULL,
[OrderID] [int] NULL,
[Name] [varchar](max) NULL,
[Phone] [varchar](max) NULL,
[Fax] [varchar](max) NULL,
[Email] [varchar](max) NULL,
CONSTRAINT [PK_Contacts] PRIMARY KEY CLUSTERED
(
[conId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[Orders] Script Date: 9/26/2017 1:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Orders](
[OrderID] [int] NOT NULL,
[LoanNumber] [varchar](max) NULL,
[LoanAmount] [money] NULL,
[ToBeInsured] [bit] NULL,
[FileNumber] [varchar](max) NULL,
[CostCenter] [varchar](max) NULL,
[Product] [varchar](max) NULL,
[Notes] [varchar](max) NULL,
[ResponseURL] [varchar](max) NULL,
[PID] [int] NULL,
[PayOffLoanNumber] [varchar](max) NULL,
[ClientCode] [varchar](max) NULL,
CONSTRAINT [PK_OrderHeader] PRIMARY KEY CLUSTERED
(
[OrderID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[Properties] Script Date: 9/26/2017 1:50:18 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Properties](
[proID] [int] IDENTITY(1,1) NOT NULL,
[OrderID] [int] NULL,
[Address] [varchar](max) NULL,
[City] [varchar](max) NULL,
[State] [varchar](max) NULL,
[Zip] [varchar](max) NULL,
[County] [varchar](max) NULL,
CONSTRAINT [PK_Property] PRIMARY KEY CLUSTERED
(
[proID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Borrowers] WITH NOCHECK ADD CONSTRAINT [FK_Borrowers_Orders] FOREIGN KEY([OrderID])
REFERENCES [dbo].[Orders] ([OrderID])
GO
ALTER TABLE [dbo].[Borrowers] NOCHECK CONSTRAINT [FK_Borrowers_Orders]
GO
ALTER TABLE [dbo].[Contacts] WITH NOCHECK ADD CONSTRAINT [FK_Contacts_Orders] FOREIGN KEY([OrderID])
REFERENCES [dbo].[Orders] ([OrderID])
GO
ALTER TABLE [dbo].[Contacts] NOCHECK CONSTRAINT [FK_Contacts_Orders]
GO
ALTER TABLE [dbo].[Properties] WITH NOCHECK ADD CONSTRAINT [FK_Properties_Orders] FOREIGN KEY([OrderID])
REFERENCES [dbo].[Orders] ([OrderID])
GO
ALTER TABLE [dbo].[Properties] NOCHECK CONSTRAINT [FK_Properties_Orders]
GO
私のGET返されます
<Order>
<Borrowers />
<ClientCode>cc1</ClientCode>
<Contacts />
<CostCenter>900-111</CostCenter>
<FileNumber>11111</FileNumber>
<LoanAmount>1111.0000</LoanAmount>
<LoanNumber>111</LoanNumber>
<Notes>notes1</Notes>
<OrderID>1</OrderID>
<PID>1</PID>
<PayOffLoanNumber>po1</PayOffLoanNumber>
<Product>letter</Product>
<Properties />
<ResponseURL>yahoo.com</ResponseURL>
<ToBeInsured>true</ToBeInsured>
</Order>
あなたが見るとおり何の連絡先はありませんか借り手など
**
UPDATE: ---------------------------------------------------
**
私は私の取得を取得し、(int型のID)作業と手順を変更することにより、正しいデータを返すようにコマンドを取得することができましたしかし
public IEnumerable<Order> Get()
{
using (FirstCloseAPIEntities entities = new FirstCloseAPIEntities())
{
var entity = entities.Orders.ToList();
List<Borrower> borrowers = entities.Borrowers.ToList();
List<Contact> contacts = entities.Contacts.ToList();
List<Property> properties = entities.Properties.ToList();
//return entities.Orders.ToList() ;
return entity;
}
}
public HttpResponseMessage Get(int id)
{
using (FirstCloseAPIEntities entities = new FirstCloseAPIEntities())
{
var entity = entities.Orders.FirstOrDefault(o => o.OrderID == id);
List<Borrower> borrowers = entities.Borrowers.Where(b => b.OrderID == id).ToList();
List<Contact> contacts = entities.Contacts.Where(c => c.OrderID == id).ToList();
List<Property> properties = entities.Properties.Where(p => p.OrderID == id).ToList();
if (entity != null)
{
return Request.CreateResponse(HttpStatusCode.OK, entity);
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Order with id = " + id.ToString() + " not found.");
}
}
}
、私はHTMLとして要求していますので、私は、エラーを得ていた:として
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'
だから私は、Global.asax.csファイルに以下を追加する必要がありました:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
これはしかし、関係なく、私はタイプapplication/xmlのためのヘッダーに入れて何を、正常な応答を私に戻って与えませんでしたapplication/json私はいつもJSONとして返信しています。
Content-Type: application/xml
accept: application/xml
accept-encoding: gzip, deflate
accept-language: en-US,en;q=0.8
user-agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36
Cache-Control: no-cache
Content-Length: 707
Content-Type: application/json; charset=utf-8
Date: Tue, 26 Sep 2017 19:46:42 GMT
Expires: -1
Pragma: no-cache
Server: Microsoft-IIS/10.0
X-Aspnet-Version: 4.0.30319
X-Powered-By: ASP.NET
X-Sourcefiles: =?UTF-8?B?YzpcdXNlcnNcZG91Zy5oYW1pbHRvblxkb2N1bWVudHNcdmlzdWFsIHN0dWRpbyAyMDE3XFByb2plY3RzXHdzRXRpdGxlXHdzRXRpdGxlXGFwaVxPcmRlcnNcMQ==?=
Raw
JSON
{
"OrderID": 1,
"LoanNumber": "111",
"LoanAmount": 1111,
"ToBeInsured": true,
"FileNumber": "11111",
"CostCenter": "900-111",
"Product": "letter",
"Notes": "notes1",
"ResponseURL": "yahoo.com",
"PID": 1,
"PayOffLoanNumber": "po1",
"ClientCode": "cc1",
"Borrowers": [
{
"borID": 1,
"OrderID": 1,
"FirstName": "Ura",
"MiddleName": "O",
"LastName": "Pepper",
"SSN": "111-11-1111"
},
{
"borID": 3,
"OrderID": 1,
"FirstName": "Ima",
"MiddleName": "J",
"LastName": "Pepper",
"SSN": "222-22-2222"
}
],
"Contacts": [
{
"conId": 1,
"OrderID": 1,
"Name": "Jackie the box",
"Phone": "414-555-1243",
"Fax": "414-222-1245",
"Email": "[email protected]"
}
],
"Properties": [
{
"proID": 1,
"OrderID": 1,
"Address": "123 Main Street",
"City": "Anytown",
"State": "WI",
"Zip": "10012
"County": "Westchester"
}
],
}
だから私はXMLで応答を取得する方法へとまだ混乱していた後、最後の部分は、この記事の上部に示すように、供給される情報を取得し、それを投稿することができることです正しい表。
"私は、お互いを参照してデータモデルを更新するテーブルに外部キーを追加する必要があると仮定していますが、そうするとさまざまなエラーが発生します。"正しい。どのようなエラー? –
私はJSONを使ってローカルで作業していますが、XMLは問題のようです。ソースをXML形式に、ヘッダーをapplication/xml(コンテンツタイプと受け入れ..)に切り替えると、415 Unsupported Mediaタイプのメッセージが表示されます。 – uwdoug79