【发布时间】:2020-05-08 20:23:57
【问题描述】:
在现有的 ASP.NET MVC 项目中,我创建了一个新的 Web API 控制器。
namespace EMSMVC.Controllers
{
public class TabletController : ApiController
{
public Call Get(int call_id)
{
using(EMSMVCEntities entities = new EMSMVCEntities())
{
return entities.Calls.FirstOrDefault(e => e.call_id == call_id);
}
}
}
}
当我尝试通过浏览器访问它时:
http://localhost:53366/Tablet/Call/157
我得到错误:
“/”应用程序中的服务器错误。找不到资源。
我的RouteConfig.cs 包含:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Dashboard", action = "Index", id = UrlParameter.Optional }
);
}
}
WebApiConfig.cs 文件包含:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
现有的控制器工作正常。
【问题讨论】:
-
不应该是
http://localhost:53366/api/Tablet/Get/157 -
@Rahul 它不起作用。
-
您能否将操作签名更改为 [HttpGet] public Call Get(int id) 并访问为localhost:53366/api/Tablet/157
-
@BhasyakaruluKottakota 我似乎正在工作。但是现在我收到错误消息
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'.Consider using a DataContractResolver if you are using DataContractSerializer or add any types not known statically to the list of known types - for example, by using the KnownTypeAttribute attribute or by adding them to the list of known types passed to the serializer. -
这是一个序列化问题。确保“Call”模型和“httpclient”的序列化同步。
标签: c# .net asp.net-mvc