c# - 如何在asp.net web api中读取json文件

标签 c# asp.net asp.net-web-api

在我的 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/

相关文章:

c# - 我必须向我的 Web API REST 方法添加显式线程吗?

c# - 为什么 GUID uniqueidentifier 显示值略有不同

c# - 在 Windows Phone 应用程序中重用 Storyboard

c# - CSLA.net - 可继承的基类

使用 Onclientclick 或 Onsubmit 都不会调用 JavaScript 函数

c# - gridview 根据值更改文本颜色

asp.net - IIS应用程序池每天崩溃几次

c# - 错误 500 "Queries cannot be applied to the response content of type ' System.Net.Http.ByteArrayContent'

c# - 在 SqlDataAdapter.Update() 中获取错误消息

javascript - 如何从 JavaScript 调用通用 WebAPI 操作?