簡體   English   中英

WebApi不能在ASP.Net中工作

[英]WebApi is not Working in ASP.Net

我是Asp.Net的新手,並嘗試在學習過程中開發一個小型Web API。

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

此Url不在瀏覽器中工作,不在Fiddler 4中。

所有引用都被添加。 我也完成了構建解決方案,但它不起作用,它們在代碼中沒有顯示錯誤。

啟用Web Api的最后一步是通過向Application_Start()方法添加以下代碼行來啟用Global.asax文件中的Web API:

WebApiConfig.Register(GlobalConfiguration.Configuration);

另外,請不要使用PluralSight教程中的端口號。您需要從Visual Studio實例運行Web應用程序項目,當它在瀏覽器中打開時,您將看到哪個端口被分配給您的 api服務。所以如果您看到它分配了端口12345,您可以調用以下URL來訪問服務操作:

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

添加屬性路由到控制器

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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM