首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用错误的内容类型反序列化ServiceStack Json

使用错误的内容类型反序列化ServiceStack Json
EN

Stack Overflow用户
提问于 2013-06-18 03:15:31
回答 1查看 384关注 0票数 2

尝试使用ServiceStack 3.9.49和CORS进行设置。

一个返回POSTed data back++的简单Echo服务。代码:

代码语言:javascript
运行
复制
[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代码:

代码语言:javascript
运行
复制
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标头,例如:

代码语言:javascript
运行
复制
if (httpRequest.ContentType == "text/plain")
    httpRequest.Headers["Content-Type"] = ContentType.Json;
EN

回答 1

Stack Overflow用户

发布于 2014-03-21 06:50:10

将ServiceStack的序列化程序反序列化为空对象是正确的行为。它往往非常宽宏大量。它创建一个空的反序列化对象,并使用它从输入中解析出的任何内容对其进行消减,这意味着如果您给它提供垃圾数据,您将得到一个空对象。

您可以通过在AppHost配置中指定以下选项来降低序列化程序的容错性:

代码语言:javascript
运行
复制
ServiceStack.Text.JsConfig.ThrowOnDeserializationError = true;

我不知道有什么方法可以修改URL来向ServiceStack表明请求是JSON格式的。此外,在ServiceStack中似乎没有任何方法可以在反序列化之前修改内容类型。因为请求的ContentType属性已经设置并且是只读的,所以即使在前面指定一个PreRequestFilter来修改头部也不会起作用。

代码语言:javascript
运行
复制
PreRequestFilters.Add((req, res) => req.Headers["Content-Type"] = "application/json");
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17155070

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档