如何在Controller中获取本地资源

时间:2013-10-02 20:48:48

标签: c# asp.net-mvc

我正在尝试这样做:

HttpContext.GetLocalResourceObject("~/Views/Shared/AnotherFolder/More/App_LocalResources/MyResourceFile.cshtml.resx", "myKey") 

但我一直在控制器中收到此错误:

The resource class for this page was not found. Please check if the resource file exists and try again.

如果我在try块中包装调用。否则,该函数将弹出。

目录结构,其中Views就在根文件夹之后:

Directory structure

我确定路径是正确的,因为我刚从资源文件的属性窗口复制它,但可能出错?虚拟路径不正确吗?

这是调试输出:

A first chance exception of type 'System.InvalidOperationException' occurred in System.Web.dll
System.Data.SqlClient.SqlException (0x80131904): Could not find stored procedure 'ELMAH_LogError'.
   at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
   at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
   at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
   at System.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString)
   at System.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean async, Int32 timeout, Task& task, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
   at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
   at Elmah.SqlErrorLog.Log(Error error)
   at Elmah.ErrorLogModule.LogException(Exception e, HttpContext context)

1 个答案:

答案 0 :(得分:0)

这篇MSDN文章指出:

  

存储在特殊App_LocalResources中的本地默认资源文件   文件夹是根据ASP.NET页面命名的。例如,如果   以下代码用于Default.aspx页面,资源文件必须   命名为Default.aspx.resx。

你没有说过你打电话的地点(或确切地说如何):

HttpContext.GetLocalResourceObject("~/Views/Shared/AnotherFolder/More/App_LocalResources/MyResourceFile.cshtml.resx", "myKey")

因此,正如文章建议的那样,如果从名为“Default.aspx”的文件中调用此方法(例如),请将资源文件重命名为“Default.aspx.resx”并改为使用此方法调用:< / p>

var resource = GetLocalResourceObject("myKey").ToString();

请注意,我已将结果分配给“资源”,因为我假设您在实际代码中执行类似的操作,还要注意需要将结果强制转换为您期望的任何类型。