[英]ServiceStack Request Body
我正在嘗試在 servicestack 和 ormlite 中編寫我的第一個 REST 服務。 不會太糟。
我設法編寫了顯示所有記錄、基於 ID 的記錄並刪除基於 ID 的記錄的代碼。
現在我開始添加和編輯記錄,我對如何從調用的請求正文中獲取數據感到困惑。
我正在做一個
POST: http://localhost:7571/equipment/create/123
與請求正文
[{"eMCo":"1","equipment":"DP112","location":"Field","manufacturer":"","model":"","modelYr":"2013","vinNumber":"","description":"Trevor","status":"A","attachToEquip":"BR118","licensePlateNo":""}]
但是在我的服務中,我無法弄清楚如何在此函數中訪問請求正文數據:
public object Post(EMEMTrev request)
{
var dbFactory = new OrmLiteConnectionFactory("Data Source=(local);Initial Catalog=Kent;Integrated Security=True", SqlServerDialect.Provider);
using (IDbConnection db = dbFactory.OpenDbConnection())
{
//base.Request.FormData[""]
db.Insert(request);
}
return null;
}
這是完整的代碼......如果你能指出我做錯的任何事情,請做!
using ServiceStack;
using ServiceStack.OrmLite;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
namespace ViewPoint
{
[Api("Enables viewiing, creation, updating and deletion of equipment from the EMEM table.")]
[Route("/equipment", "GET")]
[Route("/equipment/detail/{equipment}", "GET")]
[Route("/equipment/delete/{equipment}", "DELETE")]
[Route("/equipment/update/{equipment}", "PATCH")]
[Route("/equipment/create/{equipment}", "POST")]
public class EMEMTrev
{
public string eMCo { get; set; }
public string equipment { get; set; }
public string Location { get; set; }
public string Manufacturer { get; set; }
public string Model { get; set; }
public string ModelYr { get; set; }
public string VINNumber { get; set; }
public string Description { get; set; }
public string Status { get; set; }
public string AttachToEquip { get; set; }
public string LicensePlateNo { get; set; }
}
public class EMEMTrevResponse
{
public string eMCo { get; set; }
public string equipment { get; set; }
public string Location { get; set; }
public string Manufacturer { get; set; }
public string Model { get; set; }
public string ModelYr { get; set; }
public string VINNumber { get; set; }
public string Description { get; set; }
public string Status { get; set; }
public string AttachToEquip { get; set; }
public string LicensePlateNo { get; set; }
public ResponseStatus ResponseStatus { get; set; } //Where Exceptions get auto-serialized
}
public class EquipmentService : Service
{
public object Get(EMEMTrev request)
{
var dbFactory = new OrmLiteConnectionFactory("Data Source=(local);Initial Catalog=Kent;Integrated Security=True", SqlServerDialect.Provider);
using (IDbConnection db = dbFactory.OpenDbConnection())
{
if (request.equipment == null)
{
List<EMEMTrev> results = db.Select<EMEMTrev>();
return results;
}
else
{
List<EMEMTrev> results = db.Select<EMEMTrev>(p => p.Where(ev => ev.equipment == request.equipment));
return results;
}
}
}
public object Delete(EMEMTrev request)
{
var dbFactory = new OrmLiteConnectionFactory("Data Source=(local);Initial Catalog=Kent;Integrated Security=True", SqlServerDialect.Provider);
using (IDbConnection db = dbFactory.OpenDbConnection())
{
db.Delete<EMEMTrev>(p => p.Where(ev => ev.equipment == request.equipment));
}
return null;
}
public object Post(EMEMTrev request)
{
var dbFactory = new OrmLiteConnectionFactory("Data Source=(local);Initial Catalog=Kent;Integrated Security=True", SqlServerDialect.Provider);
using (IDbConnection db = dbFactory.OpenDbConnection())
{
//base.Request.FormData[""]
db.Insert(request);
}
return null;
}
public object Patch(EMEMTrev request)
{
var dbFactory = new OrmLiteConnectionFactory("Data Source=(local);Initial Catalog=Kent;Integrated Security=True", SqlServerDialect.Provider);
using (IDbConnection db = dbFactory.OpenDbConnection())
{
db.Update(request);
}
return null;
}
}
}
任何幫助將不勝感激!
謝謝
更新代碼:
服務設備.cs
using ServiceStack;
using ServiceStack.OrmLite;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Web;
namespace ViewPoint
{
[Api("Enables viewiing, creation, updating and deletion of equipment from the EMEM table. Use a POST to create an EMEM or a PUT to update one.")]
[Route("/equipment", "GET,POST,PUT")]
[Route("/equipment/{equipment}", "GET,DELETE")]
public class EMEMTrev
{
public string eMCo { get; set; }
public string equipment { get; set; }
public string location { get; set; }
public string manufacturer { get; set; }
public string model { get; set; }
public string modelYr { get; set; }
public string vinNumber { get; set; }
public string description { get; set; }
public string status { get; set; }
public string attachToEquip { get; set; }
public string licensePlateNo { get; set; }
}
public class EMEMTrevResponse
{
public EMEMTrev emem { get; set; }
public ResponseStatus ResponseStatus { get; set; } //Where Exceptions get auto-serialized
}
public class EquipmentService : Service
{
public object Get(EMEMTrev request)
{
var dbFactory = new OrmLiteConnectionFactory("Data Source=(local);Initial Catalog=Kent;Integrated Security=True", SqlServerDialect.Provider);
using (IDbConnection db = dbFactory.OpenDbConnection())
{
if (request == null)
{
List<EMEMTrev> results = db.Select<EMEMTrev>();
return results;
}
else
{
List<EMEMTrev> results = db.Select<EMEMTrev>(p => p.Where(ev => ev.equipment == request.equipment));
return results;
}
}
}
public object Delete(EMEMTrev request)
{
var dbFactory = new OrmLiteConnectionFactory("Data Source=(local);Initial Catalog=Kent;Integrated Security=True", SqlServerDialect.Provider);
using (IDbConnection db = dbFactory.OpenDbConnection())
{
db.Delete<EMEMTrev>(p => p.Where(ev => ev.equipment == request.equipment));
}
return new HttpResult
{
StatusCode = HttpStatusCode.NoContent,
Headers =
{
{HttpHeaders.Location, this.Request.AbsoluteUri.CombineWith(request.equipment)}
}
};
}
public object Post(EMEMTrev request)
{
var dbFactory = new OrmLiteConnectionFactory("Data Source=(local);Initial Catalog=Kent;Integrated Security=True", SqlServerDialect.Provider);
using (IDbConnection db = dbFactory.OpenDbConnection())
{
db.Insert(request);
}
return new HttpResult()
{
StatusCode = HttpStatusCode.Created,
Headers =
{
{HttpHeaders.Location, base.Request.AbsoluteUri.CombineWith(request.equipment)}
}
};
}
public object Put(EMEMTrev request)
{
var dbFactory = new OrmLiteConnectionFactory("Data Source=(local);Initial Catalog=Kent;Integrated Security=True", SqlServerDialect.Provider);
using (IDbConnection db = dbFactory.OpenDbConnection())
{
db.Update(request);
}
return new HttpResult
{
StatusCode = HttpStatusCode.NoContent,
Headers =
{
{HttpHeaders.Location, base.Request.AbsoluteUri.CombineWith(request.equipment)}
}
};
}
}
}
應用主機.cs:
using System.Configuration;
using ServiceStack;
using ServiceStack.Auth;
using ServiceStack.Configuration;
using ServiceStack.Data;
using ServiceStack.OrmLite;
[assembly: WebActivator.PreApplicationStartMethod(typeof(ViewPoint.App_Start.AppHost), "Start")]
/**
* Entire ServiceStack Starter Template configured with a 'Hello' Web Service and a 'Todo' Rest Service.
*
* Auto-Generated Metadata API page at: /metadata
* See other complete web service examples at: https://github.com/ServiceStack/ServiceStack.Examples
*/
namespace ViewPoint.App_Start
{
public class AppHost : AppHostBase
{
public AppHost() //Tell ServiceStack the name and where to find your web services
: base("StarterTemplate ASP.NET Host", typeof(EquipmentService).Assembly) { }
public override void Configure(Funq.Container container)
{
//Set JSON web services to return idiomatic JSON camelCase properties
ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
//Configure User Defined REST Paths
//Routes
// .Add<Hello>("/hello")
// .Add<Hello>("/hello/{Name*}");
//Uncomment to change the default ServiceStack configuration
//SetConfig(new HostConfig {
//});
//Enable Authentication
//ConfigureAuth(container);
//Register all your dependencies
//container.Register(new TodoRepository());
}
/* Example ServiceStack Authentication and CustomUserSession */
private void ConfigureAuth(Funq.Container container)
{
var appSettings = new AppSettings();
//Default route: /auth/{provider}
Plugins.Add(new AuthFeature(() => new CustomUserSession(),
new IAuthProvider[] {
new CredentialsAuthProvider(appSettings),
new FacebookAuthProvider(appSettings),
new TwitterAuthProvider(appSettings),
new BasicAuthProvider(appSettings),
}));
//Default route: /register
Plugins.Add(new RegistrationFeature());
//Requires ConnectionString configured in Web.Config
var connectionString = ConfigurationManager.ConnectionStrings["AppDb"].ConnectionString;
container.Register<IDbConnectionFactory>(c =>
new OrmLiteConnectionFactory(connectionString, SqlServerDialect.Provider));
container.Register<IUserAuthRepository>(c =>
new OrmLiteAuthRepository(c.Resolve<IDbConnectionFactory>()));
container.Resolve<IUserAuthRepository>().InitSchema();
}
public static void Start()
{
new AppHost().Init();
}
}
}
您的問題與 JSON 數據和 DTO 之間的大小寫差異有關。 映射區分大小寫。 填充equipment
參數是因為案例匹配,但其余屬性不匹配。
您可以通過將此行添加到AppHost
配置來解決此問題。
JsConfig.EmitCamelCaseNames = true;
這組串行映射location
在你的JSON數據來Location
你的DTO和其他屬性,當你序列,並處理轉換回來。
因此,您可以訪問請求參數上的屬性,而不是通過原始數據。
您的服務看起來不錯。 我無法立即看到它有任何問題,我認為問題可能在於您如何調用服務。
下面的這些方法將有助於調試問題。 我建議您嘗試使用這個簡單的 HTML 頁面調用客戶端,看看是否填充了必填字段。
創建一個文件,將其命名為test.html
並將其與 ServiceStack 服務程序集放在bin
文件夾中,然后導航到您的服務路徑http://localhost:7571/test.html
。
<!doctype html>
<html>
<head>
<title>Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
function send()
{
// Send data to the service
$.ajax({
type: "POST",
url: "/equipment/create/DP112",
contentType: "application/json",
data: JSON.stringify({
eMCo: "1",
equipment: "DP112",
location: "Field",
manufacturer: "",
model: "",
modelYr: "2013",
vinNumber: "",
description: "Trevor",
status: "A",
attachToEquip: "BR118",
licensePlateNo: ""
})
}).done(function(result){
});
}
</script>
</head>
<body>
<button onclick="send()">Send Request</button>
</body>
</html>
此 html 文件應提供格式正確的請求。
還可以考慮通過將此行添加到您的 AppHost 配置來添加請求記錄器。 然后轉到http://localhost:7571/requestlogs
。 請參閱此處了解更多信息。
Plugins.Add(new RequestLogsFeature());
如果客戶端請求中未設置正確的內容類型,則 ServiceStack 不會將值填充到請求中。 將請求的contentType
設置為application/json
有效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.