从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;
}

Webapiconfig

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(

您必须调用以下内容:

http://yourhostname/Api/Version/acCompany?term=someString

您的Controller名称是Version而不是AutoComplete

因为您的控制器名称是Version,而不是AutoComplete。你只是用错了网址。

将返回类型更改为IActionResult,并将列表包装在OkObjectResult中,就像这样…

return Ok(co);

您可以返回这样的JsonResult,而不是返回List。

[HttpGet]
public JsonResult 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 Json(new { co {);
}

我知道这已经通过查询字符串得到了回答。但是正如OP在评论中所提到的,如果你想像这样调用你的端点:http://localhost:5555/api/Version/acCompany/somevalue

然后您需要修改您的webapi操作参数,使其在id而不是term中执行,如下所示:

[HttpGet]
public List<AutoCompleteCompany> acCompany(string id)
{
   // rest of your action code would make use of id instead of term
}

在该更改之后,您应该能够将其调用为http://localhost:5555/api/Version/acCompany/somevalue.当调用此项时,id将接受某个值。

你需要使用id的原因是因为它们在webapiconfig.cs.中的配置方式

最新更新