尝试使用ServiceStack 3.9.49和CORS进行设置。
一个返回POST
ed data back++的简单Echo
服务。代码:
[Route("/echo")]
public class EchoRequest
{
public string Name { get; set; }
public int? Age { get; set; }
}
public class RequestResponse
{
public string Name { get; set; }
public int? Age { get; set; }
public string RemoteIp { get; set; }
public string HttpMethod { get; set; }
}
public class EchoService : Service
{
public RequestResponse Any(EchoRequest request)
{
var response = new RequestResponse
{
Age = request.Age,
Name = request.Name,
HttpMethod = base.Request.HttpMethod,
RemoteIp = base.Request.RemoteIp
};
return response;
}
}
AppHost Configure
代码:
public override void Configure(Container container)
{
ServiceStack.Text.JsConfig.EmitCamelCaseNames = true;
SetConfig(new EndpointHostConfig
{
DefaultContentType = ContentType.Json,
GlobalResponseHeaders = new Dictionary<string, string>(),
DebugMode = true
});
Plugins.Add(new CorsFeature());
PreRequestFilters.Add((httpRequest, httpResponse) => {
//Handles Request and closes Responses after emitting global HTTP Headers
if (httpRequest.HttpMethod == "OPTIONS")
httpResponse.EndServiceStackRequest();
});
RequestFilters.Add((httpRequest, httpResponse, dto) =>
{
httpResponse.AddHeader("Cache-Control", "no-cache");
});
}
当使用Content-Type: application/json发送POST
(在正文中包含json对象)时,一切都很正常。
但是,当发送相同的内容并将Content-Type
设置为text/plain
时,将调用正确的方法,但EchoRequest
中的数据为null
。
这是正确的行为吗?如果json对象作为application/json
发送,则必须将Content-Type
设置为POST
是,有没有可能以某种方式覆盖它,例如在url中?根据我的理解,在url中使用?format=json只会影响返回的数据...
最后一个问题,在将请求反序列化为方法之前,是否可以修改请求的Content-Type
标头,例如:
if (httpRequest.ContentType == "text/plain")
httpRequest.Headers["Content-Type"] = ContentType.Json;
发布于 2014-03-21 06:50:10
将ServiceStack的序列化程序反序列化为空对象是正确的行为。它往往非常宽宏大量。它创建一个空的反序列化对象,并使用它从输入中解析出的任何内容对其进行消减,这意味着如果您给它提供垃圾数据,您将得到一个空对象。
您可以通过在AppHost配置中指定以下选项来降低序列化程序的容错性:
ServiceStack.Text.JsConfig.ThrowOnDeserializationError = true;
我不知道有什么方法可以修改URL来向ServiceStack表明请求是JSON格式的。此外,在ServiceStack中似乎没有任何方法可以在反序列化之前修改内容类型。因为请求的ContentType属性已经设置并且是只读的,所以即使在前面指定一个PreRequestFilter来修改头部也不会起作用。
PreRequestFilters.Add((req, res) => req.Headers["Content-Type"] = "application/json");
https://stackoverflow.com/questions/17155070
复制相似问题