0

我正在开发一个 ASP.NET MVC 4 应用程序。从数据库中获取信息并在网页上显示在这个阶段进展顺利。然后我决定与我的应用程序的进展并行开发一个 Web API。到目前为止一切顺利,直到我尝试使用本地主机上的 URL 对其进行测试。

当我尝试它时,我收到了 HTTP 错误 500。

http://localhost:23375/我从 VS 2010 运行应用程序,它在我的浏览器中打开。最后,我附加了我的 API 调用,将其带到:

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

当我按下回车键时,我得到了错误。为什么会这样,我该如何解决?

以下是相关代码:

性能控制器.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();
        }

    }
}

全球.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"                    
            }
        );
    }



}
}
4

2 回答 2

0

我遇到了同样的问题,我想我把它缩小到 HTTP 的 Accept 标头。当您通过 JavaScript 调用 API 时,将 Accept 标头作为 JSON 或 XML 传递,它可以工作。

当您从浏览器拨打电话时,您要求的是不同的内容类型,因此您会收到错误 500。

我仍然无法确认,但看起来是这样的。

于 2012-08-01T16:22:23.147 回答
0

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

于 2012-09-01T22:13:34.683 回答