我可以通过Javascript使用“/ api / X”路径调用我的服务。 (POST动词)
我可以使用client.Get(serviceUrl)调用相同的服务没有请求对象 //客户端是JsonServiceClient
但是client.Send(X)不起作用。我得到了奇怪的404 NotFound响应?
我错过了什么吗?我该如何调试问题?
到目前为止,费用是5小时!
核对表
代码:
在AppHost.cs中
base.SetConfig(new EndpointHostConfig
{
GlobalResponseHeaders =
{
{ "Access-Control-Allow-Origin", "*" },
{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
},
AppendUtf8CharsetOnContentTypes = new HashSet<string> { ContentType.Html },
DebugMode = true, //Show StackTraces in service responses during development
LogFactory = new ElmahLogFactory(new Log4NetFactory())
});
//Set JSON web services to return idiomatic JSON camelCase properties
ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
//Configure User Defined REST Paths
Routes.Add<JobRequest>("/job");
在Model.cs中
[DataContract]
public class JobRequest : IReturn<JobRequestResponse>
{
[DataMember]
public string JobRequestEnum { get; set; }
[DataMember]
public string JobData { get; set; }
}
[DataContract]
public class JobRequestResponse : IHasResponseStatus
{
[DataMember]
public string Message { get; set; }
[DataMember]
public ResponseStatus ResponseStatus { get; set; }
}
在JobService.cs
中 public class JobService : ServiceStack.ServiceInterface.Service
{
public JobRepository Repository { get; set; }
public object Any(JobRequest request)
{
return new JobRequestResponse() { Message = "ok" };
}
}
在Javascript.js // IT WORKS
$.ajax({
type: 'POST',
url: "/api/job",
data: '{ "jobRequestEnum": "test", "jobData": "test" }',
dataType: "json",
contentType: "application/json",
success: function (res) {
debugger;
}
});
在CallJob.js //它不工作
string serviceUrl = ConfigurationManager.AppSettings["serviceUrl"];
using (JsonServiceClient client = new JsonServiceClient(serviceUrl))
{
var request = new JobRequest() { JobData = "test", JobRequestEnum = "test" };
var response = client.Send<JobRequestResponse>(request);
}
答案 0 :(得分:2)
如果您在Request DTO上添加[Route]
,请执行以下操作:
[Route("/job")]
[DataContract]
public class JobRequest : IReturn<JobRequestResponse>
{
[DataMember]
public string JobRequestEnum { get; set; }
[DataMember]
public string JobData { get; set; }
}
然后C#客户端将能够在客户端上使用自定义/job
路由,例如:
var client = new JsonServiceClient(serviceUrl);
var request = new JobRequest { JobData = "test", JobRequestEnum = "test" };
JobRequestResponse response = client.Post(request);
每当您没有在Request DTO上定义Route或指定Response类型时,例如:
var response = client.Send<JobRequestResponse>(request);
您没有使用IReturn<T>
C#客户端API,因此它会向pre-defined route发送 POST ,其中包含:{/ p>
POST /json/syncreply/JobsRequest
{ ... }
正如您所假设的那样/jobs
(即C#客户端无法知道路由信息,因此它会回退到使用预定义的路由)。
否则,如果您想将路径定义保留在AppHost中,您可以通过在C#调用中提供它来强制它使用预定义的URL,例如:
client.Post<JobRequestResponse>("/job", request);
同样在新API中(当您使用IReturn<T>
标记时),您不再需要Request DTO +'Response'命名约定,并且可以自由选择您需要的任何名称,因此它没有是JobRequestResponse
听起来有点尴尬:))