2012-08-01 88 views
0

我正在开发一个ASP.NET MVC 4应用程序。在这个阶段从数据库获取信息并在网页上显示。然后我决定我想开发一个Web API,并且与我的应用程序的进展并行。到目前为止这么好,直到我尝试使用本地主机上的URL进行测试。C#/ ASP.NET - 通过URL调用Web API操作? :HTTP错误500

当我尝试过了,我得到了一个HTTP错误500

我从2010年VS运行应用程序,并在浏览器中打开了http://localhost:23375/。在此结束时,我附加了API调用,将其添加到:

http://localhost:23375/api/Performance/ShowMachines 

当我按Enter时,出现错误。为什么这样,我该如何解决?

下面是相关代码:

PerformanceController.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Net.Http; 
using System.Web.Http; 

using PerfMon.Models; 

namespace PerfMon.Controllers 
{ 
    public class PerformanceController : ApiController 
    { 

     PerfMonDataRepository perfRep = new PerfMonDataRepository(); 

     // GET /performance/machines 
     [HttpGet] 
     public IQueryable<Machine> ShowMachines() 
     { 
      return perfRep.GetAllMachines(); 
     } 

    } 
} 

的Global.asax.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.Http; 
using System.Web.Mvc; 
using System.Web.Optimization; 
using System.Web.Routing; 

namespace PerfMon 
{ 
    // Note: For instructions on enabling IIS6 or IIS7 classic mode, 
    // visit http://go.microsoft.com/?LinkId=9394801 

public class WebApiApplication : System.Web.HttpApplication 
{ 
    protected void Application_Start() 
    { 
     AreaRegistration.RegisterAllAreas(); 

     FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); 
     RouteConfig.RegisterRoutes(RouteTable.Routes); 
     BundleConfig.RegisterBundles(BundleTable.Bundles); 
    } 

    public static void RegisterRoutes(RouteCollection routes) 
    { 

     routes.IgnoreRoute("{resource}.axd/{*pathInfo}"); 

     routes.MapHttpRoute(
      name: "Machines", 
      routeTemplate: "api/{controller}/{action}", 
      defaults: new { 
       controller = "Performance", 
       action = "ShowMachines"      
      } 
     ); 
    } 



} 
} 

回答

0

问题是,当我创建.dbml文件并将表格拖放到其中时,自动生成的DataContext类创建了EntitySet对象来表示外键关系。我创建了简单的类,使用get sand集返回JSON,而不是DataContext中的类,不包括EntitySet对象。结果,它像一个魅力。显然EntitySets是不可序列化的,因此给出了500错误。

0

我遇到了同样的问题,我想我也收窄直到HTTP的Accept头。当您通过JavaScript将Accept标头作为JSON或XML传递给API时,它将起作用。

当您从浏览器调用,你所要求的不同的内容类型,所以你得到一个错误500

我仍然无法确认,但看起来像。

+0

不,这不是很不幸,因为当我尝试调用本地生成的数组而不必从浏览器访问数据库时(由于URL调用API),我得到了XML中的信息或JSON形式。 – praetor 2012-08-01 23:54:31