简体   繁体   中英

How to read json file in asp.net web api

In my asp.web api 2.0 project I have a Json file, where all the error codes are mapped. I want to read the json file in order to return response to the caller.

I am unable to read the same, however if I use console application following code works, any suggestion will be helpful.

Code that works in console application:

 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());    
 }

Using above code provides assembly as null in web api project, hence I changed it to following:

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;
}

The exception I get is:

Operation is not valid due to the current state of the object.

With Server.MapPath it is easy for ASP.NET to find your files but the file still have to be inside of the application root folder, here is some official documentation on this function.

Just place file inside your root folder, and then use Server.MapPath this will allow your ASP.NET application to find your file in the Server file system.

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

You can try this :

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

    object jsonObject = JsonConvert.DeserializeObject(allText);
    return jsonObject;
}

this code returns json text

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM