c# - 创建 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);
}
解决方案
正如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 语句来优雅地处理可能的异常,比如你得到的异常是一种很好的做法。
除此之外,如果您在生产服务器上具有相关访问权限,您可以尝试授予应用程序(以及正在执行它的用户)访问所述位置的权限。
推荐阅读
- azure - 在 Azure ML 中将本地计算与 Estimator 结合使用
- visual-studio - 如何限制组织中的特定用户从我们的办公室 IP 外部访问 Azure DevOps
- android - Google WebRTC 是否支持 Cisco Open H.264?
- c# - 是否可以将短时区字符串作为 EST CET PST 转换为 C# 中的 TimeZoneInfo?
- php - 在输入字段上使用类属性声明值
- javascript - 不同系统中打印窗口的不同边距
- java - 可以使用杰克逊从内部 json 对象中获取字段吗?
- python - 为什么我的代码在 Eclipse 控制台中比在 Eclipse 的 PyDev Python 控制台中运行得更快?
- android - Ionic 3 - 未安装应用程序。包裹似乎已损坏
- android - 是否可以从 CameraPreview 中抓取一个像素?