2012-08-01 89 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