首页 > 解决方案 > 从 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)

标签: c#asp.net-mvcasp.net-web-api

解决方案


因为您的控制器名称是版本,而不是自动完成。您只是使用了错误的网址。


推荐阅读