【发布时间】: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