2016-08-23 64 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