首页 > 解决方案 > 创建 json 文件时的生产出现错误 500 内部服务器错误

问题描述

在 localhost 创建 json 文件没有问题,但在生产中创建 json 文件得到错误代码 500 内部服务器错误。为什么我得到错误,我该如何解决?

代码 jquery

            var url = '@Url.Action("CreateJsonFileContent", "xxx")';
            $.ajax({
                url: url,
                type: "POST",
                data: JSON.stringify(content),
                dataType: "json",
                contentType: "application/json; charset=utf-8"
            }).done(function (data) {
                console.log(data);
            }).fail(function (jqXHR, textStatus, errorThrown) {
                console.log("Status : " + textStatus);
            })

代码控制器(部分)

        [HttpPost]
    public JsonResult CreateJsonFileContent(string PlantName, List<string> EmailName)
    {
            string json = JsonConvert.SerializeObject(contents);
            
            string pathFile = System.Configuration.ConfigurationManager.AppSettings["pathJson"];
            string jsonPath = Path.Combine(pathFile + "\\" +  PlantName.Replace(" ", "") + ".json");

            if (System.IO.File.Exists(jsonPath)) System.IO.File.Delete(jsonPath);

            using (TextWriter tw = new StreamWriter(jsonPath))
            {
                tw.WriteLine(json);
            }
            return Json(message, JsonRequestBehavior.AllowGet);
       
    }

标签: c#jqueryasp.netasp.net-mvcasp.net-core

解决方案


正如Nick猜测的那样,您的 Web 应用程序很可能没有执行文件操作的权限,或者它正在尝试访问(读取和/或写入)不存在的位置。

确定正在发生的事情的一种方法是让您在生产服务器上启用并激活日志记录。另一种(但可能非常不安全的方式)是在控制器方法中添加一个 try-catch 语句,并将所有 IO 操作放在该 try-catch 语句中(参见下面的示例)。

    [HttpPost]
    public JsonResult CreateJsonFileContent(string PlantName, List<string> EmailName)
    {
            string json = JsonConvert.SerializeObject(contents);
            
            string pathFile = System.Configuration.ConfigurationManager.AppSettings["pathJson"];
            string jsonPath = Path.Combine(pathFile + "\\" +  PlantName.Replace(" ", "") + ".json");


            try
            {
               if (System.IO.File.Exists(jsonPath)) System.IO.File.Delete(jsonPath);

                using (TextWriter tw = new StreamWriter(jsonPath))
                {
                   tw.WriteLine(json);
                }
                return Json(message, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                // log error here
                return Json(new
                {
                     message = "An error occurred while creating the file",
                     details = ex.ToString()
                }, JsonRequestBehavior.AllowGet);
            }           
    }

我称之为可能非常不安全的原因是您将服务器错误的详细信息暴露给最终用户。在我看来,这绝不应该被允许。话虽如此,使用 try-catch 语句来优雅地处理可能的异常,比如你得到的异常是一种很好的做法。

除此之外,如果您在生产服务器上具有相关访问权限,您可以尝试授予应用程序(以及正在执行它的用户)访问所述位置的权限。


推荐阅读