@manhng

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.

[HttpGet]
[Route("UserAppointments/{email}")]
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.

[HttpGet]
[Route("UserAppointments/{email}")]
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

    [Route("Data")]
    [HttpGet]
    public IHttpActionResult GetData()
    {
        var data = GetAllTrainings();    
        return new TrainingDataResponse(data.ToList(), Request);
    }

JavaScript (JS) đỉnh cao

June 9, 2020 10:42

JavaScript (JS) đỉnh cao (edit)

https://1loc.dev/

This project is developed by Nguyen Huu Phuoc

https://github.com/phuoc-ng/1loc

Products

You might be interested in my products:

Product Description
01. 1 LOC Favorite JavaScript utilities in single line of code
02. Blur Page A browser extension to hide sensitive information on a web page
03. CSS Layout A collection of popular layouts and patterns made with CSS
04. Fake Numbers Generate fake and valid numbers
05. Form Validation The best validation library for JavaScript
06. HTML DOM How to manage HTML DOM with vanilla JavaScript
07. React PDF Viewer A React component to view a PDF document

Resources

Design pattern implementations in TypeScript

https://github.com/torokmark/design_patterns_in_typescript

Algorithms and data structures implemented in JavaScript with explanations and links to further readings

https://github.com/trekhleb/javascript-algorithms

JavaScript Style Guide

https://github.com/nghuuphuoc/javascript

A collection of awesome browser-side JavaScript libraries, resources and shiny things.

https://github.com/nghuuphuoc/awesome-javascript

1) Functional Programmer

https://www.freecodecamp.org/news/how-point-free-composition-will-make-you-a-better-functional-programmer-33dcb910303a/

Trở thành Functional Programmer - Phần 6

https://viblo.asia/p/tro-thanh-functional-programmer-phan-6-EyORkbjEGqB

Link của các phần trước: Phần 1, Phần 2, Phần 3, Phần 4, Phần 5

2) Kỹ thuật Currying trong JavaScript

https://nvksolution.com/ky-thuat-currying-trong-javascript/

3) Point Free

Point-free gotchas in JavaScript

https://dev.to/danhomola/point-free-gotchas-in-javascript--3pfi

Point-free in JavaScript

https://lucasmreis.github.io/blog/pointfree-javascript/

Function Composition point-free style

https://medium.com/tech-tajawal/function-composition-point-free-style-54a209946e6

Side effects may include, but are not limited to

  • changing the file system
  • inserting a record into a database
  • making an HTTP call
  • mutations
  • printing to the screen/logging
  • obtaining user input
  • querying the DOM
  • accessing system state

Functional JS #7: Point-free style

https://medium.com/dailyjs/functional-js-7-point-free-style-b21a1416ac6a

JavaScript (JS)

December 26, 2019 15:03

JavaScript JS (edit)

JavaScript: Set

document.getElementById(id).attribute = new_value;
document.getElementById("Username").value = window.Username;
document.getElementById("Password").value = window.Password;
document.getElementById("RememberPassword").checked = window.RememberMe === 'True';

JavaScript: Checkbox

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/checkbox

jQuery (1.6+):

// Check
$("#checkbox").prop("checked", true);

// Uncheck
$("#checkbox").prop("checked", false);
<!DOCTYPE html>
<html>
<body>

Checkbox: <input type="checkbox" id="myCheck">

<button onclick="check()">Check Checkbox</button>
<button onclick="uncheck()">Uncheck Checkbox</button>

<script>
function check() {
document.getElementById("myCheck").checked = true;
}

function uncheck() {
document.getElementById("myCheck").checked = false;
}
</script>

</body>
</html>

JavaScript: Check null

element1 = document.getElementById(id);

if(element1 != null)
{
    //code to set the value variable.
}

References

Input Type: text, password, checkbox, radio, hidden, file, submit

Textarea

Select > Option

http://javascript-coder.com/html-form/html-form-tutorial-p1.phtml

http://javascript-coder.com/html-form/html-form-tutorial-p2.phtml

Thế giới JavaScript

August 6, 2017 15:56

Cách học tốt nhất là bắt đầu từ khái niệm

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Details_of_the_Object_Model

https://thachpham.com/

https://thachpham.com/category/web-development/javascript

https://viblo.asia/

https://viblo.asia/p/cac-bai-stackoverflow-ma-lap-trinh-vien-javascript-phai-doc-l5XRBJkWRqPe

https://kipalog.com/

https://kipalog.com/posts/Javascript---Nhung-kho-hieu-trong-cau-lenh-dieu-kien-if-va-phep-toan-so-sanh

https://toidicodedao.com/

https://toidicodedao.com/2016/02/23/series-javascript-sida-oop-trong-javascript/

https://nhungdongcodevui.com/

https://nhungdongcodevui.com/2016/12/11/vuot-qua-cac-bai-phong-van-javascript/

https://freetuts.net/tim-hieu-javascript-hoisting-403.html

1) OOP

Object-oriented-programming-features

+ Class, Object, Variables, Functions

+ Abstract class, interface, inheritance, encapsulation, polymorphism

+ Inheritance: dùng Prototype để viết kế thừa trong JavaScript

+ Polymorphism: dùng Constructor để diễn tả tính đa hình

+ Encapsulation: dùng trang này

/*
  Polymorphism means "many forms" and in programming describes the ability
  for objects to present the same interface for different behaviors. So calling
  man.sayHello() and woman.sayHello() would result in different output, even 
  though the method call is the same.
*/

function Person(gender) {
  this.gender = gender;
  this.sayHello = function () {
    console.log("Hello, I am a " + this.gender);
  }
}

var man = new Person("man");
var woman = new Person("woman");
man.sayHello(); // --> "Hello, I am a man"
woman.sayHello(); // --> "Hello, I am a woman"

2) Design patterns

Prototype pattern:

Module pattern:

Observer pattern: User the .apply() or .call()

Singleton pattern:

https://scotch.io/bar-talk/4-javascript-design-patterns-you-should-know

What does it mean that Javascript is a prototype based language?

Prototypal inheritance is a form of object-oriented code reuse. Javascript is one of the only [mainstream] object-oriented languages to use prototypal inheritance. Almost all other object-oriented languages are classical.

In classical inheritance, the programmer writes a class, which defines an object. Multiple objects can be instantiated from the same class, so you have code in one place which describes several objects in your program. Classes can then be organized into a hierarchy, furthering code reuse. More general code is stored in a higher-level class, from which lower level classes inherit. This means that an object is sharing code with other objects of the same class, as well as with its parent classes.

In the prototypal inheritance form, objects inherit directly from other objects. All of the business about classes goes away. If you want an object, you just write an object. But code reuse is still a valuable thing, so objects are allowed to be linked together in a hierarchy. In javascript, every object has a secret link to the object which created it, forming a chain. When an object is asked for a property that it does not have, its parent object will be asked... continually up the chain until the property is found or until the root object is reached.

Each function in JavaScript (which are objects themselves) actually has a member called "prototype", which is responsible for providing values when an object is asked for them. Having this member allows the constructor mechanism (by which objects are constructed from functions) to work. Adding a property to the prototype of a function object will make it available to the constructed object, as well as to all of the objects which inherit from it.

Advantages

There may not be a hard and fast rule as to why prototypal inheritance is an advantageous form of code-reuse. Code reuse itself is advantageous, and prototypal inheritance is a sensible way of going about it. You might argue that prototypal inheritance is a fairly simple model of code reuse, and that code can be heavily reused in direct ways. But classical languages are certainly able to accomplish this as well.

Sidenote: @Andrew Hedges makes a good point, that there are actually many prototypal languages. It's worth noting that these others exist, but also worth noting that none of them are anything close to mainstream. NewtonScript seemed to have some traction for a while, but died with its platform. It's also possible to extend some modern languages in ways which add prototypal capabilities.

3) Function declaration & Function expression

Declare function:

function helloWorld() {
  alert('Hello World');
}

Anonymous function:

var helloWold = function() {
  alert('Hello World');
}

Another anonymous function:

(function() {
  alert('Hello World');
})

Self-Executing Anonymous Functions or How to Write Clean Javascript

http://esbueno.noahstokes.com/post/77292606977/self-executing-anonymous-functions-or-how-to-write

(function() {
	var Person = {
		sayHello: function() {
			alert('Hello World');
		}
	}
})();

(function() {

	var Person = {

		init: function() {
			this.form = $('#form');
			this.bindEvents();
		},

		bindEvents: function() {
			this.form.on('submit', this.showName);
		},

		showName: function(event) {
			event.preventDefault();

			alert(this.form.find('input[type=text]').val());
		}
	}

	Person.init();

})();

Self-executing anonymous function

http://markdalgleish.com/2011/03/self-executing-anonymous-functions/

(function(){ console.log('Hello World!'); })();

(function(window, document, $, undefined){ var foo; console.log(foo === undefined); //Returns 'true' })(window, document, jQuery);

Anonymous function:

(function(){
//Normal code goes here
})

Self-invoking functions in JavaScript (or Immediately Invoked Function Expressions)

http://blog.mgechev.com/2012/08/29/self-invoking-functions-in-javascript-or-immediately-invoked-function-expression/

(function (w, d, $) {
   //body
}(window, document, jQuery));

// Usually the use of self-invoking functions is in the module pattern. It happens when we keep the reference to the function’s return value. Exactly the return value is the public API of the defined module:

var module = (function () {
    //private
    return {
    //public
    }
}());

4) Hoisting

5) Strick mode: "use strick"

6) The "this" keyword and Bind(), Call() Apply()

Việc coi function cũng như là object trong JavaScript

7) Callback function

$(document).ready(function(){});

8) Promise

Việc lạm dụng sử dụng quá nhiều callback function sẽ rất khó để quản lý, Promise ra đời để giải quyết vấn đề đó.

9) Async/Await Javascript

https://viblo.asia/

10) Closure 

11) Data type

ES5: Boolean, Number, String, Object, Array, null, undefined

ES6: Symbol, Reflect, and Proxy

12) Operator

So sánh dùng từ khóa "==" và "==="

13) Href attribute for JavaScript link: "#" OR "javascript:void(0)"?

 

14) How to set default value

function Person(name, age, projs) {

    this.name = name || "Manh"; // String

    this.age = age || 34; // Number

    this.projects = projs || []; // Array

}

Categories

Recent posts