[ASP.NET CORE MVC] 共通ライブラリで Cookieメソッドを作って使う方法

inno
2022-04-07 14:09 1063 0

[ASP.NET CORE MVC] 共通ライブラリで Cookieメソッドを作って使う方法

共通ライブラリにcookie(クッキー)を管理するメソッドを作ってControllerで利用する方法について説明します。

 

「System.Web.cs」ファイル追加

「System.Web.cs」ファイルを新しく作って以下の内容を記述します。 

namespace System.Web
{

    public static class HttpContext
    {
        private static Microsoft.AspNetCore.Http.IHttpContextAccessor m_httpContextAccessor;
        public static void Configure(Microsoft.AspNetCore.Http.IHttpContextAccessor httpContextAccessor)
        {
            m_httpContextAccessor = httpContextAccessor;
        }

        public static Microsoft.AspNetCore.Http.HttpContext Current
        {
            get
            {
                return m_httpContextAccessor.HttpContext;
            }
        }
    }
}

 

 

Startup.cs

Startup.csは2か所追記します。

1. 「ConfigureServices」に「services.AddHttpContextAccessor();」を追記。

public void ConfigureServices(IServiceCollection services)
{
	services.AddControllersWithViews();
	services.AddHttpContextAccessor();
}

 

2. 「Configure」に「System.Web.HttpContext.Configure(app.ApplicationServices.GetRequiredService());」を追記。

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseExceptionHandler("/Home/Error");
    }

    System.Web.HttpContext.Configure(app.ApplicationServices.GetRequiredService());

    app.UseStaticFiles();

    app.UseRouting();

    app.UseAuthorization();

    app.UseEndpoints(endpoints =>
    {
        endpoints.MapControllerRoute(
            name: "default",
            pattern: "{controller=Home}/{action=Index}/{id?}");
    });
	
}

 

 

共通ライブラリ作成

新しいクラス「Inno.Common.Common.cs」を追加してCookie設定に必要なメソッドを作成し共通ライブラリとして使いたいと思います。

まず、シンプルに作成すると以下のようになります。

using System.Web;

namespace Inno.Common
{
    public static class Common
    {
        // Cookie設定
        public static void SetCookie(string _key, string _value)
        {
            HttpContext.Current.Response.Cookies.Append(_key, HttpUtility.UrlEncode(_value));
        }

        // Cookie取得
        public static string GetCookie(string _key)
        {
            return HttpContext.Current.Request.Cookies[_key];
        }

        // Cookie削除        
        public static void DelCookie(string _key)
        {
            HttpContext.Current.Response.Cookies.Delete(_key);
        }
    }
}

 

CookieOptionsを設定して利用する方法は以下の通りです。

個人的には以下の方法を利用します。

using System;
using System.Web;

namespace Inno.Common
{
    public static class Common
    {
        // Cookie設定
        public static void SetCookie(string _key, string _value)
        {

            var _cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions()
            {
                Path = "/",
                Expires = new DateTimeOffset(DateTime.Now.AddDays(1)),
                Domain = "http://www.innoya.com"
            };

            HttpContext.Current.Response.Cookies.Append(_key, HttpUtility.UrlEncode(_value), _cookieOptions);
        }

        // Cookie取得
        public static string GetCookie(string _key)
        {
            return HttpContext.Current.Request.Cookies[_key];
        }

        // Cookie削除        
        public static void DelCookie(string _key)
        {
            var _cookieOptions = new Microsoft.AspNetCore.Http.CookieOptions()
            {
                Path = "/",
                Expires = new DateTimeOffset(DateTime.Now.AddDays(-1)),
                Domain = "http://www.innoya.com"
            };

            HttpContext.Current.Response.Cookies.Delete(_key,_cookieOptions);
        }
    }
}

 

 

Controllerでライブラリを使ってCookieを設定

Controllerで共通ライブラリに作ったCookie関連メソッドを以下のように使います。

using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using InnoWeb.Models;
using Inno.Common;


namespace InnoWeb.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger _logger;

        public HomeController(ILogger logger)
        {
            _logger = logger;
        }

        public IActionResult Index()
        {
            //Cookie設定
            Common.SetCookie("UserID", "inno");

            //Cookie取得
            ViewBag.UserID = Common.GetCookie("UserID");

            return View();
        }
    }
}

 

以上です。
後は応用して使ってください。

コメント