【问题标题】:How to read json file in asp.net web api如何在 asp.net web api 中读取 json 文件
【发布时间】:2019-09-11 16:49:51
【问题描述】:

在我的 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;
}

我得到的例外是:

由于对象的当前状态,操作无效。

【问题讨论】:

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


    【解决方案1】:

    使用Server.MapPath ASP.NET 很容易找到您的文件,但文件仍然必须在应用程序根文件夹中,这里有一些官方的documentation 关于此功能。

    只需将文件放在根文件夹中,然后使用Server.MapPath 这将允许您的 ASP.NET 应用程序在服务器文件系统中找到您的文件。

    string json = File.ReadAllText(Server.MapPath("~/files/myfile.json"));
    

    【讨论】:

    • 我能够使用 Server.MapPath 解决它,即使我将文件保存在不同的文件夹中。感谢您的帮助。
    【解决方案2】:

    你可以试试这个:

        public object Get()
    {
        string allText = System.IO.File.ReadAllText(@"c:\data.json");
    
        object jsonObject = JsonConvert.DeserializeObject(allText);
        return jsonObject;
    }
    

    此代码返回 json 文本

    【讨论】:

      猜你喜欢
      • 2021-11-12
      • 1970-01-01
      • 1970-01-01
      • 2017-05-13
      • 1970-01-01
      • 2013-04-26
      • 2021-12-14
      • 2017-10-22
      • 2015-09-27
      相关资源
      最近更新 更多