如何使用 ASP.NET MVC5 将 ErrorCode 转换为字符串?
How to convert ErrorCode to String with ASP.NET MVC5?
我正在尝试使用 ASP.NET MVC5 将 ERRORCODE
转换为字符串,
使用 ASP.NET MVC3,我们可以使用以下代码将错误代码转换为字符串:
// Attempt to register the user
MembershipCreateStatus createStatus;
ErrorCodeToString(createStatus);
但是对于 ASP.NET MVC5,使用 ErrorCodeToString
显示错误
因为它是未定义的。
Last_EDIT
HttpStatusCode 属于 Mvc3ToolsUpdateWeb_Default.Models 是否有与 mvc5 相同的名称空间?
::::::::::
这是错误
您可以使用以下方法获取表示错误代码的字符串值:
public String ErrorCodeToString(int errorCode){
return ((System.Net.HttpStatusCode)errorCode).ToString();
}
上述方法不需要异常处理,因为传递错误值时不会抛出异常。发生的情况是,如果索引不可用,输入数字将被转换为字符串。
附加信息:
您可以使用以下方法执行相反的操作:
public int ErrorToErrorCode(String error){
try{
return (int)Enum.Parse(typeof(System.Net.HttpStatusCode), error);
}
catch(Exception ex){
//Log the exception
return -1; // or a value indicating the error has occurred
}
如果您不喜欢 try
和 catch
,也可以使用 Enum.TryParse
。
有关 System.Net.HttpStatusCode
的更多信息,您可以参考以下 MSDN 主题:HttpStatusCode Enumeration
根据你的代码你可以把这个
ModelState.AddModelError("",
((System.Net.HttpStatusCode)createStatus).ToString());
我正在尝试使用 ASP.NET MVC5 将 ERRORCODE
转换为字符串,
使用 ASP.NET MVC3,我们可以使用以下代码将错误代码转换为字符串:
// Attempt to register the user
MembershipCreateStatus createStatus;
ErrorCodeToString(createStatus);
但是对于 ASP.NET MVC5,使用 ErrorCodeToString
显示错误
因为它是未定义的。
Last_EDIT
HttpStatusCode 属于 Mvc3ToolsUpdateWeb_Default.Models 是否有与 mvc5 相同的名称空间?
::::::::::
这是错误
您可以使用以下方法获取表示错误代码的字符串值:
public String ErrorCodeToString(int errorCode){
return ((System.Net.HttpStatusCode)errorCode).ToString();
}
上述方法不需要异常处理,因为传递错误值时不会抛出异常。发生的情况是,如果索引不可用,输入数字将被转换为字符串。
附加信息:
您可以使用以下方法执行相反的操作:
public int ErrorToErrorCode(String error){
try{
return (int)Enum.Parse(typeof(System.Net.HttpStatusCode), error);
}
catch(Exception ex){
//Log the exception
return -1; // or a value indicating the error has occurred
}
如果您不喜欢 try
和 catch
,也可以使用 Enum.TryParse
。
有关 System.Net.HttpStatusCode
的更多信息,您可以参考以下 MSDN 主题:HttpStatusCode Enumeration
根据你的代码你可以把这个
ModelState.AddModelError("", ((System.Net.HttpStatusCode)createStatus).ToString());