在我的 asp.web api 2.0 项目中,我有一个 Json 文件,其中映射了所有错误代码。我想读取 json 文件以便将响应返回给调用者。
我无法阅读相同的内容,但是如果我使用控制台应用程序跟随代码工作,任何建议都会有所帮助。
在控制台应用程序中工作的代码:
var assembly = Assembly.GetExecutingAssembly();
using (var stream = new StreamReader(assembly.GetManifestResourceStream("ConsoleApp24.Utilities.StatusCodes.json") ?? throw new InvalidOperationException()))
{
var status = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
}
使用上面的代码在 web api 项目中提供程序集为 null,因此我将其更改为以下内容:
var assembly = GetWebEntryAssembly();
using (var stream = new StreamReader(assembly.GetManifestResourceStream("PaymentAccount.Api.Resources.StatusCodes.json") ?? throw new InvalidOperationException()))
{
var status = JsonConvert.DeserializeObject<RootObject>(stream.ReadToEnd());
}
private Assembly GetWebEntryAssembly()
{
if (System.Web.HttpContext.Current == null ||
System.Web.HttpContext.Current.ApplicationInstance == null)
{
return null;
}
var type = System.Web.HttpContext.Current.ApplicationInstance.GetType();
while (type != null && type.Namespace == "ASP")
{
type = type.BaseType;
}
return type == null ? null : type.Assembly;
}
我得到的异常(exception)是:
Operation is not valid due to the current state of the object.
最佳答案
与 Server.MapPath
ASP.NET 很容易找到你的文件,但文件仍然必须在应用程序根文件夹内,这里是一些官方 documentation在这个功能上。
只需将文件放在根文件夹中,然后使用 Server.MapPath
这将允许您的 ASP.NET 应用程序在服务器文件系统中找到您的文件。
string json = File.ReadAllText(Server.MapPath("~/files/myfile.json"));
关于c# - 如何在asp.net web api中读取json文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57893638/