ラベル C# の投稿を表示しています。 すべての投稿を表示
ラベル C# の投稿を表示しています。 すべての投稿を表示

2018年10月7日日曜日

ASP.NET Core Web API - html ファイルの利用

ASP.NET Core Web API で html ファイルを利用(表示)する方法です。

Startup.cs ファイルの Configure メソッドに、app.UseStaticFiles() を呼び出します。すると、wwwroot フォルダ配下の html ファイルを表示できるようになります。

public class Startup
{
    ...

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();
        app.UseStaticFiles(); //追加
    }
}

ASP.NET Core Web API - GET と POST

ASP.NET Core Web API で GET メソッドと POST メソッドの実装方法を調べてみました。


ValuesController.cs (一部抜粋)
[Route("api/[controller]")]
[ApiController]
public class ValuesController : ControllerBase
{
    // GET api/values
    [HttpGet]
    public ActionResult<IEnumerable<string>> Get()
    {
        return new string[] { "value1", "value2" };
    }

    // POST api/values
    [HttpPost]
    public void Post([FromBody] string id)
    {
    }
}

index.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <input type="button" value="click" onclick="get()" />
    <input type="button" value="post" onclick="post()" />
    <script>
        function get(){
            var httpRequest = new XMLHttpRequest();
            httpRequest.onreadystatechange = function () {
                if (httpRequest.readyState === 4) {
                    if (httpRequest.status === 200) {
                        console.log("GET: 通信成功");
                    } else {
                        console.log("GET: 通信失敗");
                    }
                }
            };
            httpRequest.onload = function () {
                console.log("GET: 通信完了");
            };
            httpRequest.open("GET", "api/values", true);
            httpRequest.send(null);
        }

        function post() {
            var httpRequest = new XMLHttpRequest();
            httpRequest.onreadystatechange = function () {
                if (httpRequest.readyState === 4) {
                    if (httpRequest.status === 200) {
                        console.log("POST: 通信成功");
                    } else {
                        console.log("POST: 通信失敗");
                    }
                }
            };
            httpRequest.onload = function () {
                console.log("POST: 通信完了");
            };
            
            httpRequest.open("POST", "api/values", true);
            httpRequest.setRequestHeader('Content-Type', 'application/json');
            httpRequest.send(JSON.stringify("id=abc"));
        }
    </script>
</body>
</html>

POST を行うときには、setRequestHeader で Content-Type に application/json を指定する必要があります。ここが分からなくてしばらく調べました。

2018年4月21日土曜日

ASP.NET MVC で URL からコントローラー名を隠す

2018/04/23 追記
ふと、属性ルーティングで済むのではないかと思い、試してみました。結果、うまくいきました。

RegisterRoutes 内で、MapMvcAttributeRoutes を呼び出します。デフォルトで定義されている MapRoute は、必要がなければ削除(コメントアウト)します。
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        //属性ルーティングの有効化
        routes.MapMvcAttributeRoutes();

        //"Home" や "Home/Index" にアクセスする必要がなければ削除
        //routes.MapRoute(
        //    name: "Default",
        //    url: "{controller}/{action}/{id}",
        //    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        //);
    }
}

続いて、ルート属性を利用して、指定します。ルートの ”/”、”/Articles”、”/Articles/Index” で Index アクションにアクセスできるように属性を 3 つ設定しています。
public class ArticlesController : Controller
{
    [Route("~/")]
    [Route("Articles")]
    [Route("Articles/Index")]
    public ActionResult Index()
    {
        return View();
    }
}

しかも、最初に参照していた stackoverflow のスレッドにも、この属性ルーティングの方法が提案されていました。よく読みましょう... (^^;)
https://stackoverflow.com/a/39948890


2018/04/22
タイトルのままです。ASP.NET MVC で URL からコントローラー名を隠す方法を調べてみました。結果、ルーティングを設定することで解決しました。

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
        //MyRoute を追加。コントローラー名を指定していないリクエストは、Articles コントローラーで捕捉
        routes.MapRoute(
            "MyRoute",
            "{action}/{id}",
            new
            {
                controller = "Articles",
                action = "Index",
                id = UrlParameter.Optional
            }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

参考:ASP.NET MVC - Removing controller name from URL
https://stackoverflow.com/questions/3337372/asp-net-mvc-removing-controller-name-from-url

2018年3月27日火曜日

ASP.NET Web API で JSON を返す方法

ASP.NET Web API で JSON を返す実装例です。

1.WebApiConfig クラス内で "text/html" フォーマットをリターンするようにします。

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

        //json を返す
        //https://stackoverflow.com/a/13277616
        config.Formatters.JsonFormatter.SupportedMediaTypes
            .Add(new MediaTypeHeaderValue("text/html"));
    }
}

2.Request.CreateReponse メソッドに、ステータスコードと、モデルのリストを渡します。すると、クライアントには JSON がリターンされます。

public class ProductsController : ApiController
{
    ...

    public HttpResponseMessage Get()
    {
        IList<IProduct> products = _rep.GetAll();

        //モデルリストから JSON に変換
        //Content Negotiation in ASP.NET Web API
        //https://docs.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/content-negotiation#serialization
        return Request.CreateResponse(HttpStatusCode.OK, products);
    }
}

2017年10月2日月曜日

ASP.NET Web API で JSON を取得する方法

Web API で JSON を取得する実装例です。

View:
<input type="button" id="apiButton" class="btn" value="Web Api Test" />

<script>
    function asyncCall() {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () {
            if ((xhr.readyState === 4) && (xhr.status === 200)) {
                var json = xhr.response;
                console.log(json);
            }
        }
        xhr.open("GET", "/api/values", true);
        xhr.send(null);
    }

    var button1 = document.getElementById("apiButton");
    button1.addEventListener("click", asyncCall, false);
</script>

Controller:
public class Item
{
    public int Id { get; set; }

    public string Name { get; set; }

    public DateTime RegisteredOn { get; set; }

    public int CategoryId { get; set; }
}


public class ValuesController : ApiController
{
    // GET api/values
    public IEnumerable<Item> Get()
    {
        List<Item> items = new List<Item>();
        items.Add(new Item { Id = 1, Name = "Toshihiko", CategoryId = 1, RegisteredOn = DateTime.Today });
        items.Add(new Item { Id = 2, Name = "Takashi", CategoryId = 1, RegisteredOn = DateTime.Today });
        return items;
    }
}

2017年6月30日金曜日

C# out キーワード

C# の out キーワードについての簡単なメモです。

out キーワードは、メソッドにオブジェクトを参照渡しすることができます。
下記例では、ModifyText メソッドでは、値のコピーが渡されます。このため ModifyText の呼び出し後に、ModifyText の呼び出し元のオブジェクト(text)そのものに変化はありません。

一方で、後続の ModifyTextOut では、引数に out キーワードを伴います。ModifyTextOut を呼び出す際にも、引数に out キーワードをつけます。out キーワードは参照渡しのため、呼び出し元で ModifyTextOut に渡される引数(out text)の、メモリのアドレスを渡しています。ModifyTextOut 内では text のアドレスを経由して、ModifyText の呼び出し元のオブジェクト(text)そのものの値を書き換えています。

class Program
{
    static void Main(string[] args)
    {
        string text = "abc";
        ModifyText(text);
        Console.WriteLine("ModifyText の後:" + text);
        ModifyTextOut(out text);
        Console.WriteLine("ModifyTextOut の後:" + text);
        Console.ReadLine();
    }

    private static void ModifyText(string param)
    {
        param = "xxx";
    }

    private static void ModifyTextOut(out string param)
    {
        param = "zzz";
    }
}

実行結果です。
C# out キーワード

2017年5月22日月曜日

C# アクセス修飾子

C# のアクセス修飾子について、それぞれの意味を確認していきます。

public:

最も制限のない状態です。
public で修飾されたメンバーは、そのメンバーを持つクラスはもちろん、継承クラス、外部アセンブリからアクセスすることができます。
public で修飾された型は外部アセンブリからアクセスすることができます。

例えば、ClassLibrary1 というアセンブリに MyClass という public クラスを定義します。このクラスには public プロパティとして MyString を定義しています。
同じアセンブリ内の、MyOtherClass というクラスからも、MyClass の MyString にアクセスすることができます。

using System;

namespace ClassLibrary1
{
    public class MyClass
    {
        public MyClass()
        {
            this.MyString = "This is my public string.";
            this.MyPrivateString = "This is my private string";
        }

        public string MyString { get; set; }

        private string MyPrivateString { get; set; }
    }

    public class MyOtherClass
    {
        public MyOtherClass()
        {
            MyClass myClassX = new MyClass();
            Console.WriteLine(myClassX.MyString);
        }
    }
}



続いて、AccessModifierTest アセンブリの Form1 クラスから MyClass クラスのインスタンスを生成し、MyString プロパティにアクセスしています。このように、public でクラスを修飾すると外部アセンブリからもアクセスが可能です。

namespace AccessModifierTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            MyClass myClass1 = new MyClass();
            Console.WriteLine(myClass1.MyString);
        }
    }
}

(以下、作成中です。)
private

protected

internal

protected internal

2017年5月18日木曜日

C# using ステートメントを利用したリソースの読み込みと開放の例

using ステートメントを利用することで読み込むリソースを必ず開放してくれます。using ステートメントで読み込むオブジェクトは、IDisposable インターフェイスを実装している必要があります。

private void button1_Click(object sender, EventArgs e)
{
    var file1 = new FileInfo("TextFile1.txt");
    using(var streamReader = file1.OpenText())
    {
        string textLine;
        while ((textLine = streamReader.ReadLine()) != null)
        {
            System.Diagnostics.Debug.WriteLine(textLine);
        }
    }
}

オブジェクトが IDisposable インターフェイスを実装していないと、ビルドエラーになります。





リンク:
C# プログラミング

2017年5月17日水曜日

ASP.NET MVC クライアントサイドの検証機能

ASP.NET MVC のクライアントサイドの検証機能を実装する例です。

前提として、ASP.NET MVC プロジェクトの App_Start/BundleConfig.cs にある RegisterBundles メソッドに jquery.validate.js が登録されていることを確認します。

public static void RegisterBundles(BundleCollection bundles)
{
    ...

    bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                "~/Scripts/jquery.validate*"));


また、_Layout.cshtml や表示するビューに jquery.validate.js が参照追加されていることを確認します。

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/bundles/jqueryval")
@Scripts.Render("~/bundles/bootstrap")
@RenderSection("scripts", required: false)


それでは簡単にモデルクラスを用意します。
Person クラスのプロパティにデータアノテーションを指定します。Required は必須入力項目となります。Range は引数で指定された数値の範囲を有効な値として取ります。ここの例にある Age プロパティでは 5 から 80 までが有効な値になります。

namespace ValidationTest.Models
{
    public class Person
    {
        [Required(ErrorMessage = "入力が必須です。")]
        public int ID { get; set; }

        [Required(ErrorMessage = "入力が必須です。")]
        public string Name { get; set; }

        [Required(ErrorMessage = "入力が必須です。")]
        [Range(5, 80, ErrorMessage ="5 から 80 の数値を入力下さい。")]
        public int Age { get; set; }
    }
}


Person クラスのインスタンスを生成します。

namespace ValidationTest.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            Person p = new Person();
            p.ID = 1;
            //p.Name = "toshihiko";
            p.Age = 19;

            return View(p);
        }

        ...
    }
}


続いて、View 側でモデルを表示するユーザーコントロールを定義します。

@model ValidationTest.Models.Person
...

@using (Html.BeginForm())
{
    <div class="form-horizontal">
        Person
        <div class="form-group">
            @Html.LabelFor(model => model.ID, htmlAttributes: new { @class = "control-label col-md-1" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.ID, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.ID, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-1" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.Age, htmlAttributes: new { @class = "control-label col-md-1" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.Age, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.Age, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            <div class="col-md-offset-2 col-md-1">
                <input type="submit" value="Save" class="btn btn-default" />
            </div>
        </div>
    </div>
}


ID、Name、Age 項目それぞれに入力検証が行われるようになりました。エラー状態では Save ボタンによるフォーム送信ができない状態になっています。