为什么我无法在Web Api中找到我的uri?

时间:2016-01-25 14:15:55

标签: asp.net asp.net-mvc

这是我在Web Api中的PUT代码。 (ASP.NET MVC 6)。

    public class VendorManagementController : ApiController
   {
    // GET 
    [Microsoft.AspNet.Mvc.HttpGet]
    public dynamic GetVendors(string sidx, string sortOrder, int page, int rows,int pkey)
    {

        var vendors = _vendorRespository.GetAllVendors().AsQueryable();
        var pageIndex = Convert.ToInt32(page) - 1;
        var pageSize = rows;
        var totalRecords = vendors.Count();
        var totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);
        if (sidx != null)
        {
            vendors = sortOrder == "asc" ? vendors.OrderBy(sidx) : vendors.OrderBy(sidx + " descending");
        }
        else
        {
            vendors = vendors.OrderBy(x => x.pkey);
        }
            vendors = vendors.Skip(pageIndex * pageSize).Take(pageSize);
        return new
        {
            total = totalPages,
            page = page,
            records = totalRecords,
            rows = (from vendor in vendors
                    select new
                    {
                        cell = new string[]
                        {
                        vendor.pkey.ToString(),
                        vendor.Company,
                        vendor.ContactName,
                        vendor.ContactPhone,
                        vendor.UserName,
                        Encoding.UTF8.GetString(vendor.UserKey),
                        vendor.Active.ToString(),
                        vendor.FacilityId.ToString(),
                        vendor.ClientID.ToString(),
                        vendor.PhotoURL,
                        vendor.PushToGP.ToString()
                        }
                    }).ToArray()
        };
    }

在视图中,我有:

jQuery(gridSelector).jqGrid({
            url: API_URL + 'GetVendors',
            datatype: 'json',
            mtype: 'GET',
            height: 'auto',
            colNames: ['pkey', 'Company', 'ContactName', 'ContactPhone', 'UserName', 'UserKey', 'Active', 'FacilityId', 'ClientId', 'PhotoURL', 'PushToGP'],
            colModel: [
                { name: 'pkey', index: 'pkey', width: 50, hidden: true },
                { name: 'Company', width: 120 },
                { name: 'ContactName', width: 110 },
                { name: 'ContactPhone', width: 120 },
                { name: 'UserName', align: "right", width: 90 },
                { name: 'UserKey', align: "right", width: 120, hidden: true },
                { name: 'Active', width: 50, edittype: "checkbox", editoptions: { value: "True:False" }, unformat: aceSwitch },
                { name: 'FacilityId', align: "right", width: 100, formatter: "integer" },
                { name: 'ClientID', align: "right", width: 100, formatter: "integer" },
                { name: 'PhotoURL', align: "right", width: 80 },
                { name: 'PushToGP', align: "right", width: 80, edittype: "checkbox", editoptions: { value: "True:False" }, unformat: aceSwitch }
            ],
            cmTemplate: { autoResizable: true, editable: true },
            rowNum: 10,
            rowList: [10, 20, 30],
            pager: pagerSelector,
            sortname: 'company',
            sortorder: "asc",
            viewrecords: true,
            jsonreader: {
                root: "rows",
                page: "page",
                total: "total",
                records:"records"
            },
            caption: "Vendor Managerment"
        });

但是,我检查页面,发现500错误。看图像。 image

在家庭控制器中:

 public class HomeController : Controller
{
    public IActionResult Index()
    {
        return View();
    }

    public IActionResult VendorManagement()
    {
        return View();
    }

Startup.cs

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        // Configure the HTTP request pipeline.

        // Add the following to the request pipeline only in development environment.
        if (env.IsDevelopment())
        {
            app.UseBrowserLink();
            app.UseErrorPage();
        }
        else
        {
            // Add Error handling middleware which catches all application specific errors and
            // send the request to the following path or controller action.
            app.UseErrorHandler("/Home/Error");
        }

        // Add static files to the request pipeline.
        app.UseStaticFiles();

        // Add MVC to the request pipeline.
        app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");

            // Uncomment the following line to add a route for porting Web API 2 controllers.
            // routes.MapWebApiRoute("DefaultApi", "api/{controller}/{id?}");
        });
    }
}

我是ASP.NET Web Api的新手。我的映射有什么问题吗?为什么我会收到500错误?

1 个答案:

答案 0 :(得分:0)

根据jqGrid documentation,它需要遵循默认的JSON格式

{ 
  "total": "xxx", 
  "page": "yyy", 
  "records": "zzz",
  "rows" : [
    {"id" :"1", "cell" :["cell11", "cell12", "cell13"]},
    {"id" :"2", "cell":["cell21", "cell22", "cell23"]},
      ...
  ]
}

如果我正确理解您的代码,那么您的方法应该返回JSON结果

请尝试修改此类代码并查看是否有帮助,

我添加了 id = vendor.pkey

    var result = new
    {
        total = totalPages,
        page = page,
        records = totalRecords,
        rows = (from vendor in vendors
                select new
                {
                    id = vendor.pkey,
                    cell = new string[]
                    {
                    vendor.pkey.ToString(),
                    vendor.Company,
                    vendor.ContactName,
                    vendor.ContactPhone,
                    vendor.UserName,
                    Encoding.UTF8.GetString(vendor.UserKey),
                    vendor.Active.ToString(),
                    vendor.FacilityId.ToString(),
                    vendor.ClientID.ToString(),
                    vendor.PhotoURL,
                    vendor.PushToGP.ToString()
                    }
                }).ToArray()
    };

    return Json(result, JsonRequestBehavior.AllowGet);