C# [ModelName]标记 模型,类名称重复。
2024-08-25 03:40:56
前几天遇到一个不算bug的bug 记录分享一下
出错情况
webapi 程序会自带一个模板 如图
点某一个接口进去后
出错原因
model实体中出现了名称一样的(并不会影响程序运行和接口的访问只针对上面类似情况)
解决方法
1.[ModelName]标记
2. 让他获取完整的命名空间
这边只说第二种解决方式 简单简洁统一
在ModelNameHelper中,用此替换类的内容。
在HelpPageSampleGenerator中,将WriteSampleObjectUsingFormatter方法替换为此方法
namespace HelpPageErrorSimulator.Areas.HelpPage.ModelDescriptions
{
internal static class ModelNameHelper
{
// Modify this to provide custom model name mapping.
public static string GetModelName(Type type)
{
ModelNameAttribute modelNameAttribute = type.GetCustomAttribute<ModelNameAttribute>();
if (modelNameAttribute != null && !String.IsNullOrEmpty(modelNameAttribute.Name))
{
return modelNameAttribute.Name;
} string modelName = type.FullName;
if (type.IsGenericType)
{
// Format the generic type name to something like: GenericOfAgurment1AndArgument2
Type genericType = type.GetGenericTypeDefinition();
Type[] genericArguments = type.GetGenericArguments();
string genericTypeName = genericType.FullName; // Trim the generic parameter counts from the name
genericTypeName = genericTypeName.Substring(, genericTypeName.IndexOf('`'));
string[] argumentTypeNames = genericArguments.Select(t => GetModelName(t)).ToArray();
modelName = String.Format(CultureInfo.InvariantCulture, "{0}Of{1}", genericTypeName, String.Join("And", argumentTypeNames));
} return modelName;
}
}
}
[SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")]
public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType)
{
if (formatter == null)
{
throw new ArgumentNullException("formatter");
}
if (mediaType == null)
{
throw new ArgumentNullException("mediaType");
} object sample = String.Empty;
MemoryStream ms = null;
HttpContent content = null;
try
{
if (formatter.CanWriteType(type))
{
ms = new MemoryStream();
content = new ObjectContent(type, value, formatter, mediaType);
formatter.WriteToStreamAsync(type, value, ms, content, null).Wait();
ms.Position = ;
StreamReader reader = new StreamReader(ms);
string serializedSampleString = reader.ReadToEnd();
if (mediaType.MediaType.ToUpperInvariant().Contains("XML"))
{
serializedSampleString = TryFormatXml(serializedSampleString);
}
else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON"))
{
serializedSampleString = TryFormatJson(serializedSampleString);
} sample = new TextSample(serializedSampleString);
}
else
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.",
mediaType,
formatter.GetType().FullName,
type.FullName));
}
}
catch (Exception e)
{
sample = new InvalidSample(String.Format(
CultureInfo.CurrentCulture,
"An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}",
formatter.GetType().FullName,
mediaType.MediaType,
UnwrapException(e).Message));
}
finally
{
if (ms != null)
{
ms.Dispose();
}
if (content != null)
{
content.Dispose();
}
} return sample;
}
如您所见,通过genericType.FullName改变了type.FullName和genericType.Name的type.Name(最后一个不是必需的)。
这样,系统将获得全名,而不是获取类的名称,包括命名空间。
现在,帮助系统甚至可以在各种命名空间中使用具有相同名称的类。
原文链接:https://www.c-sharpcorner.com/UploadFile/d132a2/workaround-in-Asp-Net-webapi-help-page/
最新文章
- JQuery的ajaxFileUpload图片上传初试
- Web标准和搜索引擎优化技术
- 在Altium_Designer_PCB_中插入图片的方法
- python3百度指数抓取
- IT男的”幸福”生活";续8
- windows下脚本检测tomcat是否启动,没有启动则启动
- [大牛翻译系列]Hadoop 翻译文章索引
- TCP/IP详解学习笔记(14)-TCP连接的未来和性能(未写完)
- github果然强大
- PowerDesigner 面向对象模型(OOM)
- Java学习日记-4 StringBuffer类和数组
- IntelliJ IDEA:给web应用提供JSTL支持
- Android之CircleImageView使用
- NLog 自定义Target
- 2018.12.1 Test
- PyQt5的安装及基本配置
- [Spring Boot] 使用多个Servlet
- Oracle 12c新特性(For DBA)
- SwipeRefreshLayout的高度测量
- 铁乐学python_md5校验两个文件的一致性
热门文章
- Spring Boot中注解事务
- 检验二叉树序列化的合理性 Verify Preorder Serialization of a Binary Tree
- Intellij IDEA 搭建Spring Boot项目(一)
- Yii 语言设置 中文提示信息
- English trip -- VC(情景课)4 A Health
- Confluence 6 LDAP 连接池配置参数
- ubuntu下使用CAJ云阅读--CAJViewer(Cloud)
- bzoj3944: Sum 杜教筛板子题
- HDU-3507 Print Article (斜率优化)
- SQL Server 存储过程 (需整理)