Welcome to my blog!

Cookies in ASP.NET Web API 2

April 1, 2022 07:05

Cookies in ASP.NET Web API 2 (edit)

All about types of Action Results in the Web API – Dhananjay Kumar (debugmode.net)

Step by Step implementing Two-Way Data Binding in Vanilla JavaScript – Dhananjay Kumar (debugmode.net)

Why you need Proxy objects in JavaScript – Dhananjay Kumar (debugmode.net)

1) CreateResponse

Set Cookie

public HttpResponseMessage Login([FromBody] LoginRequest loginRequest)
var accessToken = "Abc...Xyz";

var httpResponse = Request.CreateResponse(httpStatusCode, response);
httpResponse.Headers.Add(ResponseHeader.RequestSubmittedAt, DateTime.Now.ToString("O"));

//Add Cookie to HttpResponseMessage
var cookie = new CookieHeaderValue("AccessToken", accessToken);
cookie.Expires = DateTimeOffset.Now.AddHours(3);
cookie.Domain = Request.RequestUri.Host;
cookie.Path = "/";
httpResponse.Headers.AddCookies(new CookieHeaderValue[] { cookie });

return httpResponse;

Get Cookie

var accessToken = string.Empty;

if (HttpContext.Current.Request.Cookies["AccessToken"] != null)
HttpCookie authCookie = HttpContext.Current.Request.Cookies["AccessToken"];
accessToken = authCookie.Value;
return accessToken;

Action Results in Web API 2 - ASP.NET 4.x | Microsoft Docs

A Web API controller action can return any of the following:

  1. void
  2. HttpResponseMessage
  3. IHttpActionResult
  4. Some other type

Depending on which of these is returned, Web API uses a different mechanism to create the HTTP response.

Return type How Web API creates the response
void Return empty 204 (No Content)
HttpResponseMessage Convert directly to an HTTP response message.
IHttpActionResult Call ExecuteAsync to create an HttpResponseMessage, then convert to an HTTP response message.
Other type Write the serialized return value into the response body; return 200 (OK).

Create Web API Response (tutorialsteacher.com)

2) CreateErrorResponse

You can return an error response to provide more detail.

public HttpResponseMessage Get()
    HttpError myCustomError = new HttpError("The file has no content or rows to process.") { { "CustomErrorCode", 42 } };
    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, myCustomError);

Would return:

    "Message": "The file has no content or rows to process.", 
    "CustomErrorCode": 42 

3) Sử dụng IHttpActionResult thông qua HttpResponseMessage

public IHttpActionResult SomeAction()
IHttpActionResult response;

//we want a 303 with the ability to set location
HttpResponseMessage responseMsg = new HttpResponseMessage(HttpStatusCode.RedirectMethod);
responseMsg.Headers.Location = new Uri("http://customLocation.blah");
response = ResponseMessage(responseMsg);
return response;

4) Sử dụng IHttpActionResult thay cho HttpResponseMessage

C# - ASP.NET WebAPI: How to use IHttpActionResult instead of HttpResponseMessage - Stack Overflow

There are two ways to deal with this

First one is simple by changing the return type and passing the HttpResponseMessage to ResponseMessage which returns a IHttpActionResult derived class.

public IHttpActionResult UserAppointments(string email = null) {
    HttpResponseMessage retObject = null;    
    if (!string.IsNullOrEmpty(email)) {
        UserAppointmentService _appservice = new UserAppointmentService();
        IEnumerable<Entities.UserAppointments> app = _appservice.GetAppointmentsByEmail(email);

        if (app.Count() <= 0) {
            var message = string.Format("No appointment found for the user [{0}]", email);
            HttpError err = new HttpError(message);
            retObject = Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, err);
            retObject.ReasonPhrase = message;
        } else {
            retObject = Request.CreateResponse(System.Net.HttpStatusCode.OK, app);
    } else {
        var message = string.Format("No email provided");
        HttpError err = new HttpError(message);
        retObject = Request.CreateErrorResponse(System.Net.HttpStatusCode.NotFound, err);
        retObject.ReasonPhrase = message;

    return ResponseMessage(retObject);

The alternative is to refactor the method to follow the syntax suggestions from Asp.Net Web API 2 documentation.

public IHttpActionResult UserAppointments(string email = null) {
    if (!string.IsNullOrEmpty(email)) {
        var _appservice = new UserAppointmentService();
        IEnumerable<Entities.UserAppointments> app = _appservice.GetAppointmentsByEmail(email);
        if (app.Count() <= 0) {
            var message = string.Format("No appointment found for the user [{0}]", email);
            return Content(HttpStatusCode.NotFound, message);
        return Ok(app);
    return BadRequest("No email provided");

Reference Action Results in Web API 2

A. Các dạng Request của Restful API

Http Method gồm có 9 loại nhưng RESTful chỉ sử dụng 4 loại phổ biến

  • GET (SELECT): Trả về một Resource hoặc một danh sách Resource.
  • POST (CREATE): Tạo mới một Resource.
  • PUT (UPDATE): Cập nhật thông tin cho Resource.
  • DELETE (DELETE): Xoá một Resource.

Tương ứng với cái tên thường gọi là CRUD (Create, Read, Update, Delete)

B. Nguyên tắc thiết kế Restful

Khi chúng ta gửi 1 request tới 1 API nào đó thì sẽ có vài status code để nhận biết như sau:

  • 200 OK – Trả về thành công cho tất cả phương thức
  • 201 Created – Trả về khi một Resource được tạo thành công.
  • 204 No Content – Trả về khi Resource xoá thành công.
  • 304 Not Modified – Client có thể sử dụng dữ liệu cache.
  • 400 Bad Request – Request không hợp lệ
  • 401 Unauthorized – Request cần có auth.
  • 403 Forbidden – bị từ chối không cho phép.
  • 404 Not Found – Không tìm thấy resource từ URI.
  • 405 Method Not Allowed – Phương thức không cho phép với user hiện tại.
  • 410 Gone – Resource không còn tồn tại, Version cũ đã không còn hỗ trợ.
  • 415 Unsupported Media Type – Không hỗ trợ kiểu Resource này.
  • 422 Unprocessable Entity – Dữ liệu không được xác thực.
  • 429 Too Many Requests – Request bị từ chối do bị giới hạn.

API được thiết kế phải rõ ràng, nhìn vào phải biết được API thực hiện cái gì

C. Ưu điểm

  • Giúp cho ứng dụng trở nên rõ ràng hơn.
  • REST URL đại diện cho resource chứ không phải là hành động.
  • Dữ liệu được trả về với nhiều định dạng khác nhau như: xml, html, rss, json …
  • Code đơn giản và ngắn gọn.
  • REST chú trọng vào tài nguyên hệ thống.

Thiết Kế RESTful API + Gọi API Bằng HttpClient ASP.NET - Viblo

All about types of Action Results in the Web API – Dhananjay Kumar (debugmode.net)

We can implement IHttpActionResult to return a list of trainings in the HTTP response message, as shown below:

//In Models
    public class TrainingDataResponse : IHttpActionResult
        List<Training> _data;
        HttpRequestMessage _request; 

        public TrainingDataResponse(List<Training> data, HttpRequestMessage request)
            _data = data;
            _request = request; 

        public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
            var response = new HttpResponseMessage()
                Content = new ObjectContent<List<Training>>(_data,new JsonMediaTypeFormatter()),
                RequestMessage = _request

            return Task.FromResult(response);


//In ApiController

    public IHttpActionResult GetData()
        var data = GetAllTrainings();    
        return new TrainingDataResponse(data.ToList(), Request);

NET 5 + Kendo React

February 26, 2021 14:26

Kendo React (edit)





.NET 5



Core features version RestApiN.vsix extension

  • Three layers projects Api, Domain and Entity
  • Automapper
  • Dependency Injection
  • UnitOfWork
  • Generic Service
  • Generic Repository with Entity Framework
  • EF lazy loading and DB concurrency errors
  • Sync and Async calls
  • Generic exception handler
  • Serilog logging with Console and File sinks
  • Migrations and seed from json objects build your empty database
  • JWT authorization/authentication for generated API
  • T4 templates - simple code generation for domain and service classes

Extended features version RestApiNEx.vsix extension

  • All core features included.
  • Swagger and Swashbuckle API documentation for .NET and Swagger authentication
  • Select between Identity Server 4 or JWT authorization/authentication for generated API
  • T4 templates - smart code generation driven by existing entity classes (inherits from BaseEntity). T4 templates generate code for related domain, service, controller and test classes based on added entity classes in single click. Great time saver!
  • XUnit integration tests project added to the solution for IS4 mode or JWT authentication mode.
  • Postman API tests as json file for import (IS4 and JWT tests). Import json and run the tests.
  • Run Postman tests with PowerShell script with Newman command line implementation
  • DDoS API attacks protection service
  • Stored procedure example added to repository

Awesome Blazor


Awesome JavaScript



ASP.NET Core 3.0 + EF Core 3.0 + Web API + Swagger + JWT

October 7, 2019 21:29

ASP.NET Core 3.0 + EF Core 3.0 + Web API + Swagger + JWT


EF Core 3.0




Authorization: Bearer eyJhb...Do

cUrl (link download)

curl -X POST "https://localhost:5001/api/v1/identity/register" -H "accept: */*" -H "Content-Type: application/json" -d "{\"email\":\"test@abc.com\",\"password\":\"Abc@123!\"}" -k

curl -X POST "https://localhost:5001/api/v1/identity/login" -H "accept: */*" -H "Content-Type: application/json" -d "{\"email\":\"test@abc.com\",\"password\":\"Abc@123!\"}" -k

curl -X POST "https://localhost:5001/api/v1/posts" -H "accept: */*" -H "Authorization: Bearer eyJhb...Do" -H "Content-Type: application/json" -d "{\"name\":\"ASP.NET Core + EF Core + WebAPI\",\"tags\":[\"ASP.NET Core\"]}" -k

Source code (link download)

IIS + System.DirectoryServices + Use C# to manage IIS + IIS Manager

October 10, 2018 22:23

Use C# To Manage IIS - Using System.DirectoryServices namespace (edit)


Use C# to manage IIS


Programmatically Manage IIS


Windows XP IIS Manager v1.7


Need to install the "IIS Metabase and IIS 6 configuration compatibility 

Read more: https://drive.google.com/file/d/19G0_FwXX-odXPnXTk6jVBWCipBODFZdV/




Creating Web API in ASP.NET Core 2.0



May 21, 2018 17:54

ASP.NET MVC (edit)






NUnit Test Adapter

May 19, 2018 09:35

NUnit Test Adapter (edit)



Cài đặt vào VS


Cài đặt thông qua Nuget







March 15, 2018 21:27


Ví dụ


<?xml version="1.0" encoding="UTF-8"?>
<Message>Your Google account is not currently enabled for this operation. Please check https://console.developers.google.com/billing to see if you have a past due balance or if the credit card (or other payment mechanism) on your account is expired. You can find additional information at https://developers.google.com/storage/docs/signup</Message>
<Details>The billing account for the requested project is disabled in state 'closed'</Details>

Dapper Log4net AutoMapper

March 13, 2018 08:35

How to use the Dapper (edit)

- Create new ASP.NET Web Application called WebApplication1 (MVC: Web Forms, MVC, Web API) based on .NET Framework 4.5.2

- Nuget packages:

  + Install-Package log4net

  + Install-Package Dapper

  + Install-Package MySql.Data

  + Install-Package AutoMapper

  + Install-Package Newtonsoft.Json

- Web.config/App.config

  + Define connection string in <connectionStrings> or <appSettings>

- Controllers/HomeController.cs

- Documentation

Dapper with MS SQL Server

- Dapper with raw SQL


- Dapper with Stored Procedure

- Sample code

Dapper with MySQL

Nuget notes

+ .NET Framework 4.5
+ ASP.NET Web API 2.2
+ Web Pages 3.2

Install-Package jQuery -Version 1.12.4
Install-Package Bootstrap -version 3.3.7
Install-Package modernizr
Install-Package Newtonsoft.json
Install-Package log4net
Install-Package Dapper -Version 1.50.2 (.NET Framework 4.5)
Install-Package Microsoft.AspNet.WebApi (-Version 5.2.4)
Install-Package Swashbuckle (-Version 5.6.0)

Web API & Swagger + OAuth2





March 2, 2018 23:19

Cách để sử dụng SqlConnection trong WebAPI, sử dụng Web Surge để test web api - Feb 22, 2018



Web Surge - Aug 19, 2017

  • Capture HTTP Requests
  • Test HTTP Requests
  • Play them back under Load
  • Summarize Results

Cách để xử lý validate với parameters (model binding) - Feb 27, 2018


JWT in ASP.NET Core Web API - Mar 1, 2018


All posts in the Secure your ASP.NET Core Web API series.

UX 8 design questions to ask



Recent posts