如何修复 ASP.NET Core MVC 中的跨站脚本 (XSS) 漏洞

问题描述 投票:0回答:1

我的 ASP.NET MVC 代码中有以下代码。 安全评估工具已报告跨站脚本 (XSS) 漏洞,地址为

返回 new JsonResult(new { response = sresponse, clientdata = model });

请参阅以下代码片段。

public ActionResult DeleteSchedule(string scheduleid)
{
    string sresponse = "Success";
    ....
    ....            
        lstSchdeuleReports = new List<ScheduleReportModel>();
        ...
        model = Newtonsoft.Json.JsonConvert.SerializeObject(lstSchdeuleReports);

        return new JsonResult(new { response = sresponse, clientdata = model });
}

如何修复此安全漏洞?

谢谢, 加根

asp.net-mvc asp.net-core xss
1个回答
0
投票

您可以通过以下方式尝试 1 通过使用html编码器

    using Newtonsoft.Json; // Ensure you have Newtonsoft.Json referenced
using System.Text.Encodings.Web; // For HtmlEncoder

public ActionResult DeleteSchedule(string scheduleid)
{
    string sresponse = "Success";

    // Serialize (it's better to avoid Newtonsoft and use .NET's built-in if possible)
    var model = JsonConvert.SerializeObject(lstSchdeuleReports);

    // Output encoding using HtmlEncoder
    var encodedModel = HtmlEncoder.Default.Encode(model); 

    return new JsonResult(new { response = sresponse, clientdata = encodedModel });
}

2 你可以尝试使用 return Json 而不是 JsonResult

 using Microsoft.AspNetCore.Mvc;
public ActionResult DeleteSchedule(string scheduleid){
    string sresponse = "Success";
 
    lstSchdeuleReports = new List<ScheduleReportModel>();
    // Use Json() method to serialize the data and apply proper encoding
            model = JsonConvert.SerializeObject(lstSchdeuleReports);

    return Json(new { response = sresponse, clientdata = lstSchdeuleReports });
}
© www.soinside.com 2019 - 2024. All rights reserved.