2015-08-28 89 views
0

我想通過本教程學習在asp.net的Web API: http://blogs.msdn.com/b/henrikn/archive/2012/02/23/using-asp-net-web-api-with-asp-net-web-forms.aspx調用的ASP.NET Web API與ASP.NET Web窗體

我有一個網站,工作正常,現在我想整合WEB API。我創建了簡單的WEB API控制器類「Controller」,將RouteTable.Routes.MapHttpRoute放在Application.Start()中的global.asax中,然後嘗試調用Api,但是我沒有獲取數據作爲輸出。

this是控制器類別

public class Controller : ApiController 
{ 
    // GET api/<controller> 
    public IEnumerable<string> Get() 
    { 
     return new string[] { "value1", "value2" }; 
    } 

    // GET api/<controller>/5 
    public string Get(int id) 
    { 
     return "value"; 
    } 

    // POST api/<controller> 
    public void Post([FromBody]string value) 
    { 
    } 

    // PUT api/<controller>/5 
    public void Put(int id, [FromBody]string value) 
    { 
    } 

    // DELETE api/<controller>/5 
    public void Delete(int id) 
    { 
    } 
} 

Glogal ASAX文件:

<script runat="server"> 

    void Application_Start(object sender, EventArgs e) 
    { 
     // Code that runs on application startup 
     RouteTable.Routes.MapHttpRoute(
      name: "DefaultApi", 
      routeTemplate: "api/{controller}/{id}", 
      defaults: new { id = System.Web.Http.RouteParameter.Optional } 
     ); 

    } 

    void Application_End(object sender, EventArgs e) 
    { 
     // Code that runs on application shutdown 

    } 

    void Application_Error(object sender, EventArgs e) 
    { 
     // Code that runs when an unhandled error occurs 

    } 

    void Session_Start(object sender, EventArgs e) 
    { 
     // Code that runs when a new session is started 

    } 

    void Session_End(object sender, EventArgs e) 
    { 
     // Code that runs when a session ends. 
     // Note: The Session_End event is raised only when the sessionstate mode 
     // is set to InProc in the Web.config file. If session mode is set to StateServer 
     // or SQLServer, the event is not raised. 

    } 

</script> 

,並試圖調用

http://localhost:56497/api/values/ http://localhost:56497/api/

,但它給錯誤:

<Error> 
<Message> 
No HTTP resource was found that matches the request URI 'http://localhost:56497/api/controller/'. 
</Message> 
<MessageDetail> 
No type was found that matches the controller named 'controller'. 
</MessageDetail> 
</Error> 

是什麼,我失去了一些東西?

回答

1

Controller控制器的名稱不是最好的選擇。公約是控制器應該有像SomethingController這樣的名字。既然你與/api/values調用它,我想你應該ValuesController將其命名爲:

public class ValuesController : ApiController 

通過它看起來像你提到的教程的方式使用完全相同的名稱。

+0

是的。有效 !!!!!非常感謝 –