c# - 从 MVC Web api 中的存储过程返回 json
问题描述
public class VersionController : ApiController
{
[HttpGet]
public List<AutoCompleteCompany> acCompany(string term)
{
DataSet ds = new DataSet();
List<AutoCompleteCompany> co= new List<AutoCompleteCompany>();
try
{
ds = getdetails(term);//privae method returns dataset
co = ds.Tables[0].ToList<AutoCompleteCompany>();
}
catch (Exception ex)
{
}
return co;
}
}
下面的属性
public class AutoCompleteCompany
{
public string Value { get; set; }
}
将数据集转换为列表
public static List<T> ToList<T>(this DataTable table) where T : new()
{
IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();
List<T> result = new List<T>();
foreach (var row in table.Rows)
{
var item = CreateItemFromRow<T>((DataRow)row, properties);
result.Add(item);
}
return result;
}
private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()
{
T item = new T();
foreach (var property in properties)
{
if (property.PropertyType == typeof(System.DayOfWeek))
{
DayOfWeek day = (DayOfWeek)Enum.Parse(typeof(DayOfWeek), row[property.Name].ToString());
property.SetValue(item, day, null);
}
else
{
if (row[property.Name] == DBNull.Value)
property.SetValue(item, null, null);
else
property.SetValue(item, row[property.Name], null);
}
}
return item;
}
Webapi配置
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(name: "DefaultApi",
routeTemplate: "Api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional });
错误:
未找到与请求匹配的 HTTP 资源
MessageDetail:在控制器“自动完成”上找不到与请求匹配的操作。
以下自定义方法有效
public string GetAccess(string id)
{
return "value3";
}
请建议一种将数据集从存储过程返回到 json 作为结果的方法(web api rest)
解决方案
因为您的控制器名称是版本,而不是自动完成。您只是使用了错误的网址。
推荐阅读
- python - Python - 将文件夹中的所有 XML 文件解析为 CSV 文件
- javascript - 如何正确使用 onload 方法使我的幻灯片切换仅在图像加载延迟加载时滑动?
- javascript - 反应原生项目卡在:unimodules-react-native-adapter:generateExpoModulesPackageList
- caching - 如何将搜索数据存储在redis db中进行缓存以获得最大的性能提升
- amazon-cloudwatch - 如何使用 CloudWatch Logs Insights 从 JSON 消息中的数组中提取数据?
- python - yolov5 不训练模型
- python - 如何一次用一组图像而不是一张一张地为模型提供图像?
- typescript - 没有导入的 TypeScript / Cypress 全局枚举
- angular - HTML页面上的http API请求Angular 12为空
- powershell - 从文件中获取内容并执行 dig 命令