【问题标题】:.net webapi manipulate response (prepend object with ")]}',\n").net webapi 操作响应(在对象前面加上“)]}',\n”)
【发布时间】:2015-09-08 15:34:39
【问题描述】:

我正在寻找一种在 Web API 2 响应之前添加以下字符串的方法 )]}',\n.

你可能知道为什么。这是 JSON 劫持保护。我有 .Net MVC 常规控制器的解决方案,但没有 Web API。

在 MCVC 中,我有特殊的 JsonNetResponse 对象,我可以在其中执行以下操作:

var serializedObject = JsonConvert.SerializeObject(Data, Formatting.None);
response.Write(")]}',\n");
response.Write(serializedObject);

我不知道在操作执行后我可以在哪里操纵响应。 也许我对 Web API 请求生命周期不太了解。我会尝试更多地寻找。

我想为所有类型的请求执行此操作:POST、GET、PUT 等。

有什么建议吗?

【问题讨论】:

  • 检查 DelegatingHandler,覆盖 SendAsync 并返回 base.SendAsync(request, cancelToken).ContinueWith(....

标签: c# json asp.net-mvc asp.net-web-api


【解决方案1】:

您要查找的内容称为DelegatingHandler。您可以派生它以挂钩到 Web API 管道并覆盖其 SendAsync 方法:

public class JsonProtector : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
                HttpRequestMessage request, CancellationToken cancellationToken)
    {
        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
        // Manipulate response here.
        return response;
    }
}

就一般知识而言,以下是 Web API 管道的组成部分:

更多关于here

【讨论】:

  • 非常感谢。实际上,我仍然无法弄清楚如何修改响应。事实上我可以读到 string responseData = await response.Content.ReadAsStringAsync();但是如何将其“放回”内容中呢?
【解决方案2】:

好的,@Yuval Itzchakov 建议的解决方案是扩展 DelegatingHandler。 这是完整的代码:

public class JsonProtector : DelegatingHandler
{
    protected async override Task<HttpResponseMessage> SendAsync(
                HttpRequestMessage request, CancellationToken cancellationToken)
    {
        HttpResponseMessage response = await base.SendAsync(request, cancellationToken);
        // Manipulate response here.
        if(response.StatusCode == System.Net.HttpStatusCode.OK)
        {
            string responseData = await response.Content.ReadAsStringAsync();
            responseData = ")]}',\n" + responseData;
            var repo = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes(responseData));
            response.Content = new StreamContent(repo);
        }
        return response;
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-04-10
    • 1970-01-01
    • 2016-11-05
    • 1970-01-01
    • 2013-06-13
    • 1970-01-01
    • 2018-02-26
    相关资源
    最近更新 更多