我在 App_Code 的 Misc 库中有一个名为 EncodePicture 的函数,它对图片进行编码。但是,当我尝试调用代码时,我发现两者都存在该函数。我查看了其他答案,例如清除临时文件,我这样做了,但没有用。 Misc 库没有命名空间,它需要它吗?
我将函数调用为:-
<img id="imgTitle" src="data:image/png;base64,@Misc.EncodePicture("/aPic/banner.jpg")" alt="" width="468" height="60" />
我知道 Misc 存在于 Universe 和 App_Code 中.....
如何解决这个问题?函数是:-
using System.Security.Cryptography;
namespace Universe
{
public class Misc
{
public static string EncodePicture(string sFilename)
{
string sEncode = "";
using (FileStream fs = new FileStream(HttpContext.Current.Server.MapPath("~" + sFilename), FileMode.Open))
{
System.IO.BinaryReader br = new BinaryReader(fs);
Byte[] bytes = br.ReadBytes((Int32)fs.Length);
sEncode = Convert.ToBase64String(bytes, 0, bytes.Length);
}
return sEncode;
}
请不要说对值进行硬编码,因为我将在其他地方使用这种样式并且不能对所有图像进行硬编码。请使用 C# 或 VB.NET。
描述:编译服务此请求所需的资源期间发生错误。请查看以下特定错误详细信息并适当修改您的源代码。
编译器错误消息:CS0433:类型“Misc”同时存在于“App_Code.keoe0a1i,Version=0.0.0.0,Culture=neutral,PublicKeyToken=null”和“Universe,Version=1.0.0.0,Culture=neutral, PublicKeyToken=null'
最佳答案
通过命名空间限定
根据您的 EncodePicture()
方法的定义位置,您可以导入适当的命名空间,以便它可以在您的 View 中调用:
namespace YourProject
{
public static class Misc
{
public static string EncodePicture(string file)
{
// Build a URL for the requested path
return file;
}
}
}
然后只需在您的 View 中添加一个 using
语句:
@using YourProject;
然后您应该可以通过以下方式调用它:
@Misc.EncodePicture(...)
或者不以完全限定的方式使用 using 语句:
@YourProject.Misc.EncodePicture(...)
通过web.config
在任何地方引用它
如果这是您希望在各种不同的 View 中使用的方法,那么您可以考虑在 web.config
中添加 namespace ,以便更容易访问它:
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<!-- Add your namespace here -->
<add namespace="YourProject" />
</namespaces>
</pages>
</system.web.webPages.razor>
关于c# - 从 View 调用库函数 (MVC C#),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37490726/