- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在 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)}
}
};
}
}
AppHost.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;
这会将序列化程序设置为将 JSON 数据中的 location
映射到 DTO 中的 Location
和其他属性,并处理转换序列化时返回。
因此您可以访问请求参数上的属性,而不是通过原始数据。
您的服务看起来不错。我无法立即看出它有任何问题,我认为问题可能出在您调用服务的方式上。
以下这些方法将有助于调试问题。我建议您尝试使用这个简单的 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
。 See here获取更多信息。
Plugins.Add(new RequestLogsFeature());
如果客户端请求中没有设置正确的内容类型,那么 ServiceStack 将不会将值填充到请求中。将请求的 contentType
设置为 application/json
有效。
关于c# - ServiceStack 请求体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21076824/
程序集,masm 嘿,我写了宏来打印存储在 dane1 段中的 1 字节值。 我将值除以 16,然后将提醒推送到堆栈,直到值==0。然后我弹出提醒将它们转换为 ASCII 码,并打印它们。 有人可以看
我在 Apache Geronimo 2.1.3 上有一个 Web 服务应用程序。 我正在使用 JAX-WS,使用 SOAP 1.1 注释 POJOS。 (使用 Sun JDK 1.5) 各种客户端都
我有一个数据变量,monthArray,它被多个消费者读取,并由单个定期更新程序线程定期更新数据。全部异步。 我已经考虑了这两个选项来安全地执行更新。 ArrayList tempArray
我有一组 3D 体。每个 Body 由 8 个点定义,每个点具有三个坐标。所有的物体都是立方体的或近似立方体的。我想用系统的点栅格“填充”立方体。坐标存储在简单的 data.frames 中。 我开发
我正在处理遗留代码,需要打补丁。 问题:一个古老的应用程序发送错误的 HTTP POST 请求。其中一个参数未经过 URL 编码。我知道这个参数总是排在最后而且我知道它的名字。我现在正尝试在运行在 t
我想在触摸屏幕时移动 sprite body ,但它不能发生...... -(void)ccTouchEnded:(UITouch *)touch withEvent:(UIEvent *)event
这个问题在这里已经有了答案: Can a union be initialized in the declaration? (3 个答案) 关闭 7 年前。 如果它是一个struct那么它就可以完成
我正在尝试获取生成 sigsys 信号的系统调用的地址!但我从 gcc 收到以下错误: gcc emulator.c -fms-extensions error: ‘siginfo_t’ has no
当我使用 Postman 进行 API 调用时,我收到一个 JSON 对象..这是我所期望的。 但是,当我像这样与 Guzzle 进行相同的调用时: $client = new \GuzzleHttp
在编码时,出现了差异。通常在编写简单的方法或构造函数时,我经常使用表达式体技术。但是,当我产生以下内容时: public class Sample : ISample { private r
我正在使用 LibGDX 创建一个新项目。 我想做的是,我将 tmx 文件中的主体加载到工作正常的关卡中。尸体也有一个 Sprite 。 问题是,我想让用户触摸场景中的某些 body 。当他们触摸 b
我的意图:在不使用 union 的情况下循环遍历一个结构的 30 个成员,所有成员都是字符数组类型,每个成员都存储对 itoa 的调用结果。在下面的代码中,我将结构体成员命名为a-z、A-D。在调用函
我必须将我的代码段之一从 C 转换为 java。代码如下。 union commandString{ char commndStr[20]; struct{ char
#include union NumericType { float value; int intvalue; }Values; int main() { Values.va
我在此代码中收到错误: fun num(num:Int):Int { if (num > 0){ print(num % 10) return num / 10
我是一名优秀的程序员,十分优秀!