【问题标题】:How to prevent escaping while making a GET request?如何在发出 GET 请求时防止转义?
【发布时间】:2019-05-01 09:25:47
【问题描述】:

我正在尝试在调用 API 代理的前端使用数据,而该 API 代理调用我的 API。在我的前端,我得到 JSON 数据返回 JSON,其中包含很多反斜杠。我怎样才能防止这种情况?请参阅下面的代码和错误:

在我的前端使用我的 API:

[HttpGet]
    public async Task<ActionResult> getCall()
    {
        string url = "http://localhost:54857/";
        string operation = "getClients";

        using (var client = new HttpClient())
        {
            //get logged in userID
            HttpContext context = System.Web.HttpContext.Current;
            string sessionID = context.Session["userID"].ToString();

            //Create request and add headers
            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            //Custom header
            client.DefaultRequestHeaders.Add("loggedInUser", sessionID);

            //Response
            HttpResponseMessage response = await client.GetAsync(operation);
            if (response.IsSuccessStatusCode)
            {
                string jsondata = await response.Content.ReadAsStringAsync();

                return Content(jsondata, "application/json");
            }
            return Json(1, JsonRequestBehavior.AllowGet);
        }
    }

我的 Api Broker 获取请求并执行此操作:

如您所见,响应内容包含很多反斜杠。

此响应将返回到我的前端,在那里我收到以下内容:

在此响应中添加了更多反斜杠。

我希望有人认识到这个问题并知道解决方案。

提前致谢!

【问题讨论】:

  • 您是否能够反序列化您的 JSON 字符串并获取所需的数据?当然,您不会在视图上显示实际的字符串。您需要对此 JSON 字符串进行反序列化并获取所需的数据以进行演示。
  • 是的,我现在显示的是 3 个反斜杠而不是 6 个。
  • 您可以使用string outputjson = jsondata.Replace("\\", ""); 删除反斜杠。

标签: c# asp.net asp.net-mvc api escaping


【解决方案1】:

我通过将字符串序列化为 JSON 对象而不是反序列化来修复它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-08
    • 2018-08-25
    • 2020-12-25
    相关资源
    最近更新 更多