2014年2月19日 星期三

在WebSite使用ASP.NET Web API

Tool:Visual Studio 2013 Ultimate
OS:Windows 8.1
.NET Framework : 4.5.1

在Visual Studio 2013 開發Web API時,若採用Web Site方式建立網站,預設沒有輔助功能可以快速建立Web API,以下步驟說明如何在WebSite建立及使用Web API

  • New Web Site

image

  • Empty

image

  • NuGet

image

image

image

 

image

image

image

image

image

Code:

<%@ Application Language="C#" %>
<%@ Import Namespace="System.Web.Http" %>
<script RunAt="server">

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

image

  • Page_Load

 

protected void Page_Load( object sender , EventArgs e ) {
  HttpClient client = new HttpClient( );
  client.BaseAddress = new Uri( "http://localhost:18541" );

  HttpResponseMessage resp = client.GetAsync( "api/values" ).Result;
  IEnumerable<string> data = null;
  if ( resp.IsSuccessStatusCode ) {
    data = resp.Content.ReadAsAsync<IEnumerable<string>>( ).Result;

  }

  foreach ( var item in data ) {
    Response.Write( item );
    Response.Write( "<br/>" );
  }
}

 

  • Test

image

 

image

沒有留言:

總網頁瀏覽量