【问题标题】:C#/ASP.NET - Calling Web API operation via URL? : HTTP Error 500C#/ASP.NET - 通过 URL 调用 Web API 操作? : HTTP 错误 500
【发布时间】:2012-08-01 01:02:25
【问题描述】:

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

当我尝试它时,我得到了一个 HTTP 错误 500。

我从 VS 2010 运行应用程序,它在我的浏览器中打开了 http://localhost:23375/。最后,我附加了我的 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();
        }

    }
}

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



}
}

【问题讨论】:

    标签: http rest asp.net-mvc-4 asp.net-web-api


    【解决方案1】:

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

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

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

    【讨论】:

    • 不,不是很遗憾,因为当我尝试调用本地制作的数组而不是必须从浏览器访问数据库时(由于对 API 的 URL 调用),我得到了以 XML 或 JSON 格式返回信息。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-17
      • 2017-01-17
      • 2014-09-02
      • 1970-01-01
      相关资源
      最近更新 更多