LoginSignup
11
17

More than 5 years have passed since last update.

ASP.NET Web APIを使ってAzure上にWeb APIサーバをつくる

Last updated at Posted at 2015-07-13

「Hello World」と返すだけのWeb APIサーバーをつくってみましょう。

Azure SDKをダウンロードしておきます。

「新しいプロジェクト」

Windows_7.jpg

「Visual C#」→「Web」→「ASP.NET Webアプリケーション」→「OK」

Windows_71.jpg

「Empty」→「Web API」→「OK」

Windows_72.jpg

「App Service plan」はてきとうに「TrialServicePlan」とでもしておきましょう。「Resource group」は「Default-Web-NorthCentralUS」を選びます。

Windows_73.jpg

しばらく待つとアプリケーションがAzureに正常にデプロイされたメッセージが表示されます。

Windows_74.jpg

Controllersフォルダに「Web API 2 コントローラー」を追加します。

Windows_75.jpg

名前はHelloWorldController.csとし、以下のように編集します。

HelloWorldController.cs
namespace CloudbitWebapi_p150713.Controllers
{
    public class HelloWorldController : ApiController
    {
        // /api/HelloWorld
        public string Get()
        {
            return "Hello world";
        }
    }
}

それでは実行してみましょう。

Windows_76.jpg

「localhost:xxxx/api/HelloWorld」にアクセスすると、XMLが返ってきます。

Windows_77.jpg

XMLはイマイチなのでJSONを返すようにしましょう。

App_StartフォルダのWebApiConfig.csを以下のように編集します。

WebApiConfig.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;
using System.Net.Http.Headers;  // <---追加

namespace CloudbitWebapi_p150713
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API の設定およびサービス

            // Web API ルート
            config.MapHttpAttributeRoutes();

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

            // 次の行を追加
            config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html") );
        }
    }
}

するとJSONが返ってきます。

Windows_78.jpg

あとはAzureに発行してお終いです。

Windows_79.jpg

お疲れさまでした!


ブログやっています:http://weed.nagoya

11
17
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
17