我正在尝试调用在 ServiceStack 中开发的宁静服务。我已经成功地调用了 Get(s),但我很难调用 Put 或 Post。我来自客户的脚本。
function savePartner(e) {
$.ajax({
type: "PUT",
contentType: "application/json; charset=utf-8",
headers: {
'X-HTTP-Method-Override': 'PUT'
},
url: "http://localhost:49190/test",
data: partnerInfoToJSON(),
complete: function (data) { alert("complete"); },
success: function (data) { alert("done"); },
error: function (data) { alert("failed");},
dataType: "json"
});
}
function partnerInfoToJSON() {
return JSON.stringify({
"Name": "TEST"
});
};
我在 fiddler 上完成了确保服务器端 API 正常工作的测试,并且可以正常工作。
我的服务代码:
[Route("/test/", "Put")]
public class TestDTO
{
public string Name { get; set; }
}
public class TestDTOResponse
{
public long ID { get; set; }
public ServiceStack.ServiceInterface.ServiceModel.ResponseStatus ResponseStatus { get; set; }
}
[EnableCors(allowedMethods: "GET,POST,PUT,DELETE")]
public class TestService : ServiceStack.ServiceInterface.Service
{
[EnableCors(allowedMethods: "GET,POST,PUT,DELETE")]
public void Options(TestDTO testDTO)
{
}
public object Put(TestDTO testDTO)
{
try
{
return "Hallo World";
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
和配置代码:
Plugins.Add(new CorsFeature());
RequestFilters.Add((httpReq, httpRes, requestDto) =>
{
if (httpReq.HttpMethod == "OPTIONS")
httpRes.End();
});
base.SetConfig(new EndpointHostConfig
{
DebugMode = true,
DefaultContentType = "application/json",
GlobalResponseHeaders = {
{ "Access-Control-Allow-Origin", "*" },
{ "Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS" },
{ "Access-Control-Allow-Headers", "Content-Type, origin, accept" },
}
});