[英]ANull reference exception when I try to get assembly version info
I'm trying to get assembly version info in <head>
section of master page. 我试图在母版页的
<head>
部分中获取程序集版本信息。 I have to do it in HTML section. 我必须在HTML部分中做到这一点。 This is row where I get null reference exception:
这是我得到空引用异常的行:
<script src="/MyViewCore.js?v=<% Response.Write( System.Diagnostics.FileVersionInfo.GetVersionInfo( System.Reflection.Assembly.GetExecutingAssembly().Location ).FileVersion.Replace( ".", "" ) ); %>" type="text/javascript"></script>
The isolated expression is: 隔离的表达式是:
System.Diagnostics.FileVersionInfo.GetVersionInfo(
System.Reflection.Assembly.GetExecutingAssembly().Location
)
.FileVersion
.Replace( ".", "" );
I can't figure out why this is problem. 我不知道为什么这是问题。
Can you help me with this issue? 您能帮我解决这个问题吗?
Your call to FileVersionInfo.GetVersionInfo
is not made in a safe manner. 您对
FileVersionInfo.GetVersionInfo
调用不是安全的。
https://msdn.microsoft.com/en-us/library/system.diagnostics.fileversioninfo.getversioninfo(v=vs.110).aspx https://msdn.microsoft.com/zh-cn/library/system.diagnostics.fileversioninfo.getversioninfo(v=vs.110).aspx
The documentation for GetVersionInfo
states it returns an object containing "only the name of the file requested" if it could not read any version information, which means the FileVersion
property will be null. GetVersionInfo
的文档指出,如果无法读取任何版本信息,它将返回一个仅包含“所请求文件的名称”的对象,这意味着FileVersion
属性将为null。
If the file did not contain version information, the FileVersionInfo contains only the name of the file requested.
如果文件不包含版本信息,则FileVersionInfo仅包含所请求文件的名称。
Note that your code is unnecessarily verbose and calling Response.Write
is unnecessary because you can use the shorthand <%=
(or the <%:
syntax for automatic HTML encoding). 请注意,您的代码不必要地冗长,也不需要调用
Response.Write
,因为您可以使用速记<%=
(或<%:
自动HTML编码的语法)。 You can also import namespaces using the <%@ Import %>
directive. 您也可以使用
<%@ Import %>
指令导入名称空间。
If you're using C# 6.0 (Visual Studio 2015) I suggest using the null-safe operator ?.
如果您使用的是C#6.0(Visual Studio 2015),建议使用null安全运算符
?.
. 。
Here's how I would do it: 这是我的处理方式:
<%@ Import Namespace="System.Diagnostics" %>
<%@ Import Namespace="System.Reflection" %>
<%
String assembly = Assembly.GetExecutingAssembly().Location;
FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo( assembly );
String version = versionInfo.FileVersion?.Replace(".", "") ?? "someFallbackValue";
%>
...
<script src="/MyViewCore.js?v=<%: version %>" type="text/javascript"></script>
I'm sure you'll agree that's considerably more readable and maintainable. 我相信您会同意它具有更高的可读性和可维护性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.