2016-08-23 65 views
1

我是Asp.Net中的新成员,并试图在学习过程中开发一个小型Web API。WebApi不能在ASP.Net中工作

WebApiConfig.cs

config.Routes.MapHttpRoute(
       name: "DefaultApi", 
       routeTemplate: "api/v1/{controller}/{id}", 
       defaults: new { id = RouteParameter.Optional } 
      ); 

TopicsController.cs

namespace MessageBoard.Controllers 
{ 
    public class TopicsController : ApiController 
    { 
     private IMessageBoardRepository _repo; 

     public TopicsController(IMessageBoardRepository repo) 
     { 
      _repo = repo; 
     } 
     public IEnumerable<Topic> Get() 
     { 

      var topics = _repo.GetTopics() 
          .OrderByDescending(t => t.Created) 
          .Take(25) 
          .ToList(); 
      return topics; 
     } 
    } 
} 

其实我看PluralSight教程。

http://localhost:50031/api/v1/topics 

此网址不能在浏览器工作不提琴手4

所有引用添加。我也完成了Build Solution,但它不工作,它们在代码中没有显示错误。

回答

2

最后一步,使网络API,它看起来像你缺少的是实现网络API在Global.asax文件中加入以下代码行到Application_Start()方法:

WebApiConfig.Register(GlobalConfiguration.Configuration); 

另外,请请勿使用PluralSight教程中的端口号。您需要从Visual Studio实例运行Web应用程序项目,并且在浏览器中打开它时,您会看到将哪个端口分配给YOUR API服务。因此,如果您会看到它分配了端口12345,例如,您可以调用以下URL来访问服务操作:

http://localhost:12345/api/v1/topics 
+0

感谢您的答案,但它的爵士在我的情况下无法正常工作。 – atifaltaf

+0

看看更新please.Are你在Visual Studio中运行Web API项目,并在拨打电话时使用正确的端口? –

+0

其工作原理是通过添加“GlobalConfiguration.Configure(WebApiConfig.Register);”在“AreaRegistration.RegisterAllAreas();”下 非常感谢先生给我的指示 – atifaltaf

1

添加属性路由到控制器

[Route("api/v1/topics")] 
public IEnumerable<Topic> Get() 
    { 

     var topics = _repo.GetTopics() 
         .OrderByDescending(t => t.Created) 
         .Take(25) 
         .ToList(); 
     return topics; 
    } 
+0

谢谢你的答案,但先生它没有在我的情况下工作。 – atifaltaf

+0

如果不是那么问题是其他地方不在路由 – Mostafiz

+0

非常感谢先生给我你的宝贵时间。 – atifaltaf