Chuyển tới nội dung
Home » Web Api In Mvc 5 | Implementation

Web Api In Mvc 5 | Implementation

(#70) Web API in MVC 5 project | mvc tutorial for beginners in .net c# | MVC By Nitish

Adding a Controller

In Web API, a controller is an object that handles HTTP requests. We’ll add a controller that can return either a list of products or a single product specified by ID.

Note

If you have used ASP.NET MVC, you are already familiar with controllers. Web API controllers are similar to MVC controllers, but inherit the ApiController class instead of the Controller class.

In Solution Explorer, right-click the Controllers folder. Select Add and then select Controller.

In the Add Scaffold dialog, select Web API Controller – Empty. Click Add.

In the Add Controller dialog, name the controller “ProductsController”. Click Add.

The scaffolding creates a file named ProductsController.cs in the Controllers folder.

Note

You don’t need to put your controllers into a folder named Controllers. The folder name is just a convenient way to organize your source files.

If this file is not open already, double-click the file to open it. Replace the code in this file with the following:


using ProductsApp.Models; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Web.Http; namespace ProductsApp.Controllers { public class ProductsController : ApiController { Product[] products = new Product[] { new Product { Id = 1, Name = "Tomato Soup", Category = "Groceries", Price = 1 }, new Product { Id = 2, Name = "Yo-yo", Category = "Toys", Price = 3.75M }, new Product { Id = 3, Name = "Hammer", Category = "Hardware", Price = 16.99M } }; public IEnumerable GetAllProducts() { return products; } public IHttpActionResult GetProduct(int id) { var product = products.FirstOrDefault((p) => p.Id == id); if (product == null) { return NotFound(); } return Ok(product); } } }

To keep the example simple, products are stored in a fixed array inside the controller class. Of course, in a real application, you would query a database or use some other external data source.

The controller defines two methods that return products:

  • The

    GetAllProducts

    method returns the entire list of products as an IEnumerable type.
  • The

    GetProduct

    method looks up a single product by its ID.

That’s it! You have a working web API. Each method on the controller corresponds to one or more URIs:

Controller Method URI
GetAllProducts /api/products
GetProduct /api/products/id

For the

GetProduct

method, the id in the URI is a placeholder. For example, to get the product with ID of 5, the URI is

api/products/5

.

For more information about how Web API routes HTTP requests to controller methods, see Routing in ASP.NET Web API.

Migrate the layout files

Copy the ASP.NET MVC project layout files to the ASP.NET Core project:

  1. In the ASP.NET Core project, right-click the Views directory, select Add > Existing Item.
  2. In the Add Existing Item dialog, navigate to the ASP.NET MVC WebApp1 project’s Views directory.
  3. Select the

    _ViewStart.cshtml

    file then select Add.

Copy the ASP.NET MVC project shared layout files to the ASP.NET Core project:

  1. In the ASP.NET Core project, right-click the Views/Shared directory, select Add > Existing Item.
  2. In the Add Existing Item dialog, navigate to the ASP.NET MVC WebApp1 project’s Views/Shared directory.
  3. Select the

    _Layout.cshtml

    file, then select Add, replacing the existing file.

In the ASP.NET Core project, open the

_Layout.cshtml

file. Make the following changes to match the completed code shown below:

Update the Bootstrap CSS inclusion to match the completed code below:

  1. Replace

    @Styles.Render("~/Content/css")

    with aelement to load

    bootstrap.css

    (see below).
  2. Remove

    @Scripts.Render("~/bundles/modernizr")

    .

The completed replacement markup for Bootstrap CSS inclusion:

Update the jQuery and Bootstrap JavaScript inclusion to match the completed code below:

  1. Replace

    @Scripts.Render("~/bundles/jquery")

    with a

    The updated

    _Layout.cshtml

    file is shown below:


    <br /> @ViewBag.Title - My ASP.NET Application<br />

    @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
    • @Html.ActionLink("Home", "Index", "Home")
    • @Html.ActionLink("About", "About", "Home")
    • @Html.ActionLink("Contact", "Contact", "Home")
    @RenderBody()

    © @DateTime.Now.Year - My ASP.NET Application

    @RenderSection("scripts", required: false)


    View the site in the browser. It should render with the expected styles in place.

    (#70) Web API in MVC 5 project | mvc tutorial for beginners in .net c# | MVC By Nitish
    (#70) Web API in MVC 5 project | mvc tutorial for beginners in .net c# | MVC By Nitish

    Create a Web API Project

    In this tutorial, you will use ASP.NET Web API to create a web API that returns a list of products. The front-end web page uses jQuery to display the results.

    Start Visual Studio and select New Project from the Start page. Or, from the File menu, select New and then Project.

    In the Templates pane, select Installed Templates and expand the Visual C# node. Under Visual C#, select Web. In the list of project templates, select ASP.NET Web Application. Name the project “ProductsApp” and click OK.

    In the New ASP.NET Project dialog, select the Empty template. Under “Add folders and core references for”, check Web API. Click OK.

    Note

    You can also create a Web API project using the “Web API” template. The Web API template uses ASP.NET MVC to provide API help pages. I’m using the Empty template for this tutorial because I want to show Web API without MVC. In general, you don’t need to know ASP.NET MVC to use Web API.

    Solve HTTP 500 errors

    There are many problems that can cause an HTTP 500 error messages that contain no information on the source of the problem. For example, if the

    Views/_ViewImports.cshtml

    file contains a namespace that doesn’t exist in the project, a HTTP 500 error is generated. By default in ASP.NET Core apps, the

    UseDeveloperExceptionPage

    extension is added to the

    IApplicationBuilder

    and executed when the configuration is Development. See an example in the following code:


    public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // 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(); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } }

    ASP.NET Core converts unhandled exceptions into HTTP 500 error responses. Normally, error details aren’t included in these responses to prevent disclosure of potentially sensitive information about the server. For more information, see Developer Exception Page.

    How To Consume WEB API in ASP.NET Core MVC | ASP.NET Web API | Read Data
    How To Consume WEB API in ASP.NET Core MVC | ASP.NET Web API | Read Data

    Introduction

    This article gives an explanation about how to create and access the Web API 2 in the ASP.NET MVC 5 application using C# and bootstrap with examples. Here I’ll also show you how to create the step by step Web API 2 in ASP.Net MVC 5 Using C# and bootstrap with a simple example. In this tutorial, you will use ASP.NET Web API 2 to create a web API and that returns a list of employees.

    Many developers/programmers who work with ASP.Net, MVC, Java, PHP, Python will have at least heard talk about the Web API. Even if any developers/programmers know on a basic level what Web API does, they are not always certain when to use Web API and how to write the code to use Web API, etc. So, in this article, I am going to explain how to create web API in asp.net MVC applications and how to use Web API in a web application with an example.

    Requirement

    • Create ASP.NET MVC Web API Application using Bootstrap.
    • Get a list of All Employees.
    • Search Employee Based on Employee ID and Display on Screen.

    What is the benefit of this approach?

    • It requires fewer server resources (it potentially enhances the scalability of the application because each client will be responsible to generate its views).
    • Raw data frequently needs less bandwidth than HTML markup. This allows data to potentially arrive more quickly to the customer. And this may improve the perceived efficiency of the app.
    • This approach supports a wide range of customers like mobile applications and tablets.

    These applications are simply referred to as endpoints that get the data and generate the local view. We refer to these terminals as Data Services (Web APIs) because they only return data and not tags.

    Web APIs are not only limited to cross-peripherals, they are also widely used in our web applications to add new functionality. Many popular sites such as Youtube, Facebook, and Twitter display public data services that we may consume in our web apps. We can merge their data into our app and provide new experiences for the new user. Those are the good things.

    How To Consume WEB API in ASP.NET MVC
    How To Consume WEB API in ASP.NET MVC

    Feedback

    Submit and view feedback for

Tổng quan về MVC API trong .NET 6

Mô hình MVC

  • Model : là nơi chứa những nghiệp vụ tương tác với dữ liệu hoặc hệ quản trị cơ sở dữ liệu (mysql, mssql… ); nó s0ẽbao gồm các class/function xử lý nhiều nghiệp vụ như kết nối database, truy vấn dữ liệu, th• êm –• xóa •– sửa• dữ liệu…

  • View : là nới chứa những giao diện như một nút bấm, khung nhập, menu, hình ảnh… nó đảm nhiệm nhiệm vụ hiển thị dữ liệu và giúp người dùng tương tác với hệ thống.

  • Controller : là nới tiếp nhận những yêu cầu xử lý được gửi từ người dùng, nó sẽ gồm những class/ function xử lý nhiều nghiệp vụ logic giúp lấy đúng dữ liệu thông tin cần thiết nhờ các nghiệp vụ lớp Model cung cấp và hiển thị dữ liệu đó ra cho người dùng nhờ lớp View.

  • Tương tác giữa các thành phần:

    • Controller tương tác với qua lại với View
    • Controller tương tác qua lại với Model
    • Model và View không có sự tương tác với nhau mà nó tương tác với nhau thông qua Controller.

API

  • API viết tắt là Application Programming Interface – giao diện lập trình ứng dụng. Nó cung cấp khả năng giao tiếp trao đổi giữa các ứng dụng thông qua internent.
  • Ở phần trước khi không sử dụng api .net 6 thì ứng dụng sẽ bao gồm phần backend và frontend chung.

  • Khi sử dụng web api thì thường sẽ chia backend ra riêng và frontend ra riêng. Và frontend website sẽ giao tiếp với backend qua API hoặc có các app mobile sẽ giao tiếp với backend qua API.

  • Ứng dụng web

  • Ứng dụng mobile

Restful là gì?

  • RESTful API là một tiêu chuẩn dùng trong việc thiết kế API cho các ứng dụng web (thiết kế Web services) để tiện cho việc quản lý các resource. Nó chú trọng vào tài nguyên hệ thống (tệp văn bản, ảnh, âm thanh, video, hoặc dữ liệu động…), bao gồm các trạng thái tài nguyên được định dạng và được truyền tải qua HTTP.

  • Các giao thức HTTP:

    • 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.
  • Những phương thức hay hoạt động này thường được gọi là CRUD tương ứng với Create, Read, Update, Delete – Tạo, Đọc, Sửa, Xóa.

Status code

  • Khi chúng ta request một API nào đó thường thì sẽ có vài status code để nhận biết sau:

    • 200 OK – Trả về thành công cho những phương thức GET, PUT, PATCH hoặc DELETE.
    • 201 Created – Trả về khi một Resouce vừa đượ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
  • Đọc thêm về http code: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status

  • Tương ứng với trong .NET 6:

    • return Ok(Value) : trả về http code 200 và kết quả.
    • return BadRequest(): trả về http code 400
    • return NotFound(): trả về http code 404
    • return NoContent(): trả về http code 204
    • return new UnsupportedMediaTypeResult(): trả về http code 415
  • Trả về HTML

    • Phương thức View() sẽ trả về một ViewResult là một HTML response.
    • Phương thức PartialView() sẽ trả về một phần của View. Sử dụng khi muốn cập nhật 1 phần của view mà không muốn load lại toàn bộ view (hữu ích trong Single Page Application)
  • Trả về File

    • FileContentResult: đọc một mảng byte và trả về như một file.
    • FileStreamResult: đọc một luồng stream và trả về một file.
    • VirtualFileResult: đọc nội dung file từ một đường dẫn tương đối trên hosting và trả về cho client.
    • PhysicalFileResult: đọc nội dung file từ một đường dẫn vật lý và trả về cho client.
  • Trả về nội dung văn bản

    • Content(value): ActionResult trả về một nội dung cụ thể như một văn bản thuần.
    • new JsonResult(value): ActionResult này trả về dữ liệu định dạng JSON. Có thể chuyển một object sang Json và trả về cho client
  • Đọc thêm về Json: https://www.w3schools.com/js/js_json_intro.asp

Thực hành MVC API

  • Tạo 5 api:

    • GET: api/categories
    • GET: api/categories/{id}
    • POST: api/categories
    • PUT: api/categories/{id}
    • DELETE: api/categories/{id}
  • Cài đặt postman để test api: https://www.postman.com/downloads/

Sử dụng Javascript làm frontend để call api

  • Tham khảo: https://learn.microsoft.com/vi-vn/aspnet/core/tutorials/web-api-javascript?view=aspnetcore-6.0

  • Bài tập về nhà: Làm chức năng create new categories, update category và delete category.

Routing trong .net core

  • Routing là quá trình điều hướng các URL request đến đúng các controller và action tương ứng.

  • Route template

    • Để url request tìm đến đúng controller action tương ứng cần có một template đóng vai trò như bản đồ chỉ dẫn.
    • Ví dụ: {controller=Post}/{action=GetByIdl}/{id?}
  • Có 2 cách để cài đặt route template:

    • Attribute routing: Ví dụ: [Route(“api/[controller]”)]
    • Convention Based Routing: https://docs.microsoft.com/en-us/aspnet/core/mvc/controllers/routing?view=aspnetcore-6.0

Environment trong .NET 6

  • Development: môi trường cho nhà phát triển

  • Staging: môi trường để testing (gần giống production)

  • Production: môi trường thực tế khách hàng sử dụng.

  • Cấu hình (configuration) trong .net

    • .NET cung cấp appsettings.json file để lưu trữ các cấu hình cho ứng dụng.
    • Ví dụ: lưu trữ cấu hình ConnectionString đến cơ sở dữ liệu, thông tin tham số ứng dụng, đường dẫn thư mục hình ảnh,….
  • Cấu hình (configuration) tùy theo môi trường

    • appsettings.json
    • appsettings.Development.json cho môi trường development.
    • appsettings.Staging.json cho môi trường staging.
    • appsettings.Production.json cho môi trường production.
  • launchSettings.json sẽ dựa vào ASPNETCORE_ENVIRONMENT để biết ứng dụng đang chạy môi trường nào.

Đọc file cấu hình appsettings.json bằng IConfiguration

  • Tham khảo: https://docs.microsoft.com/en-us/aspnet/core/fundamentals/configuration/?view=aspnetcore-6.0

  • Binding data trong file cấu hình thành object với IOptions

    • Khai báo dependence injection:

      builder.Services.Configure (builder.Configuration.GetSection("Position"));
    • Sử dụng IOptions Inject vào constructor:
  • Khai báo dependence injection:
  • Lấy giá trị connection string từ appsettings.json

Tham khảo:

  • https://medium.com/@joespinelli_6190/mvc-model-view-controller-ef878e2fd6f5
  • https://www.geeksforgeeks.org/benefit-of-using-mvc/
  • API là gì? Tại sao API được sử dụng nhiều hiện nay?

  • https://www.guru99.com/what-is-api.html
  • https://viblo.asia/p/restful-api-la-gi-1Je5EDJ4lnL
  • https://developer.mozilla.org/en-US/docs/Web/HTTP/Status
  • https://learn.microsoft.com/vi-vn/aspnet/core/tutorials/web-api-javascript?view=aspnetcore-6.0

All rights reserved

Upgrade from ASP.NET MVC and Web API to ASP.NET Core MVC

This article shows how to upgrade an ASP.NET Framework MVC or Web API app to ASP.NET Core MVC using the Visual Studio .NET Upgrade Assistant and the incremental update approach.

Next Steps

  • For a more complete example of an HTTP service that supports POST, PUT, and DELETE actions and writes to a database, see Using Web API 2 with Entity Framework 6.
  • For more about creating fluid and responsive web applications on top of an HTTP service, see ASP.NET Single Page Application.
  • For information about how to deploy a Visual Studio web project to Azure App Service, see Create an ASP.NET web app in Azure App Service.
[WebAPI-NET5] #1 - Tạo API đầu tiên
[WebAPI-NET5] #1 – Tạo API đầu tiên

Controllers and views

  • Copy each of the methods from the ASP.NET MVC


    HomeController

    to the new

    HomeController

    . In ASP.NET MVC, the built-in template’s controller action method return type is ActionResult; in ASP.NET Core MVC, the action methods return

    IActionResult

    instead.

    ActionResult

    implements

    IActionResult

    , so there’s no need to change the return type of the action methods.

  • Copy the


    About.cshtml

    ,

    Contact.cshtml

    , and

    Index.cshtml

    Razor view files from the ASP.NET MVC project to the ASP.NET Core project.

Migrate the layout file

  • Copy the


    _ViewStart.cshtml

    file from the ASP.NET MVC project’s Views directory into the ASP.NET Core project’s Views directory. The

    _ViewStart.cshtml

    file has not changed in ASP.NET Core MVC.

  • Create a Views/Shared directory.

  • Optional: Copy


    _ViewImports.cshtml

    from the FullAspNetCore MVC project’s Views directory into the ASP.NET Core project’s Views directory. Remove any namespace declaration in the

    _ViewImports.cshtml

    file. The

    _ViewImports.cshtml

    file provides namespaces for all the view files and brings in Tag Helpers. Tag Helpers are used in the new layout file. The

    _ViewImports.cshtml

    file is new for ASP.NET Core.

  • Copy the


    _Layout.cshtml

    file from the ASP.NET MVC project’s Views/Shared directory into the ASP.NET Core project’s Views/Shared directory.

Open

_Layout.cshtml

file and make the following changes (the completed code is shown below):

  • Replace


    @Styles.Render("~/Content/css")

    with aelement to load

    bootstrap.css

    (see below).

  • Remove


    @Scripts.Render("~/bundles/modernizr")

    .

  • Comment out the


    @Html.Partial("_LoginPartial")

    line (surround the line with

    @*...*@

    ). For more information, see Migrate Authentication and Identity to ASP.NET Core

  • Replace


    @Scripts.Render("~/bundles/jquery")

    with a

    The updated

    _Layout.cshtml

    file is shown below:


    <br /> @ViewBag.Title - My ASP.NET Application<br />

    @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
    • @Html.ActionLink("Home", "Index", "Home")
    • @Html.ActionLink("About", "About", "Home")
    • @Html.ActionLink("Contact", "Contact", "Home")

    @*@Html.Partial("_LoginPartial")*@

    @RenderBody()

    © @DateTime.Now.Year - My ASP.NET Application

    @RenderSection("scripts", required: false)


    View the site in the browser. It should now load correctly, with the expected styles in place.

    • Optional: Try using the new layout file. Copy the layout file from the FullAspNetCore project. The new layout file uses Tag Helpers and has other improvements.
    Học lập trình web từ A-Z (phần 5): ASP NET WEB API căn bản 1
    Học lập trình web từ A-Z (phần 5): ASP NET WEB API căn bản 1

    Create the ASP.NET Core project

    Create a new empty ASP.NET Core web app with the same name as the previous project (WebApp1) so the namespaces in the two projects match. Having the same namespace makes it easier to copy code between the two projects. Create this project in a different directory than the previous project to use the same name.

    • Optional: Create a new ASP.NET Core app using the Web Application project template. Name the project WebApp1, and select an authentication option of Individual User Accounts. Rename this app to FullAspNetCore. Creating this project saves time in the conversion. The end result can be viewed in the template-generated code, code can be copied to the conversion project, or compared with the template-generated project.

    Solve HTTP 500 errors

    There are many problems that can cause an HTTP 500 error message that contains no information on the source of the problem. For example, if the

    Views/_ViewImports.cshtml

    file contains a namespace that doesn’t exist in the project, an HTTP 500 error is generated. By default in ASP.NET Core apps, the

    UseDeveloperExceptionPage

    extension is added to the

    IApplicationBuilder

    and executed when the environment is Development. This is detailed in the following code:


    public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } }

    ASP.NET Core converts unhandled exceptions into HTTP 500 error responses. Normally, error details aren’t included in these responses to prevent disclosure of potentially sensitive information about the server. For more information, see Developer Exception Page.

    Consuming Web API In ASP.NET MVC | CRUD Operations In ASP.NET MVC with Web API
    Consuming Web API In ASP.NET MVC | CRUD Operations In ASP.NET MVC with Web API

    Additional resources

    This article shows how to start migrating an ASP.NET MVC project to ASP.NET Core MVC 2.2. In the process, it highlights many of the things that have changed from ASP.NET MVC. Migrating from ASP.NET MVC is a multi-step process. This article covers:

    • Initial setup
    • Basic controllers and views
    • Static content
    • Client-side dependencies.

    For migrating configuration and Identity code, see Migrate configuration to ASP.NET Core and Migrate Authentication and Identity to ASP.NET Core.

    Note

    The version numbers in the samples might not be current, update the projects accordingly.

    Using F12 to View the HTTP Request and Response

    When you are working with an HTTP service, it can be very useful to see the HTTP request and response messages. You can do this by using the F12 developer tools in Internet Explorer 9. From Internet Explorer 9, press F12 to open the tools. Click the Network tab and press Start Capturing. Now go back to the web page and press F5 to reload the web page. Internet Explorer will capture the HTTP traffic between the browser and the web server. The summary view shows all the network traffic for a page:

    Locate the entry for the relative URI “api/products/”. Select this entry and click Go to detailed view. In the detail view, there are tabs to view the request and response headers and bodies. For example, if you click the Request headers tab, you can see that the client requested “application/json” in the Accept header.

    If you click the Response body tab, you can see how the product list was serialized to JSON. Other browsers have similar functionality. Another useful tool is Fiddler, a web debugging proxy. You can use Fiddler to view your HTTP traffic, and also to compose HTTP requests, which gives you full control over the HTTP headers in the request.

    Cổ phiếu top 2 mai tăng: VGS, TLH, DIG, DXG Cảnh giá vùng 1200 | Nhận định thị trường chứng khoán
    Cổ phiếu top 2 mai tăng: VGS, TLH, DIG, DXG Cảnh giá vùng 1200 | Nhận định thị trường chứng khoán

    Search by ID




There are several ways to get jQuery. In this example, I used the Microsoft Ajax CDN. You can also download it from http://jquery.com/, and the ASP.NET “Web API” project template includes jQuery as well.

Getting a List of Products

To get a list of products, send an HTTP GET request to “/api/products”.

The jQuery getJSON function sends an AJAX request. The response contains array of JSON objects. The

done

function specifies a callback that is called if the request succeeds. In the callback, we update the DOM with the product information.


$(document).ready(function () { // Send an AJAX request $.getJSON(apiUrl) .done(function (data) { // On success, 'data' contains a list of products. $.each(data, function (key, item) { // Add a list item for the product. $('

  • ', { text: formatItem(item) }).appendTo($('#products')); }); }); });
  • Getting a Product By ID

    To get a product by ID, send an HTTP GET request to “/api/products/id”, where id is the product ID.


    function find() { var id = $('#prodId').val(); $.getJSON(apiUrl + '/' + id) .done(function (data) { $('#product').text(formatItem(data)); }) .fail(function (jqXHR, textStatus, err) { $('#product').text('Error: ' + err); }); }

    We still call

    getJSON

    to send the AJAX request, but this time we put the ID in the request URI. The response from this request is a JSON representation of a single product.

    Calling the Web API with Javascript and jQuery

    In this section, we’ll add an HTML page that uses AJAX to call the web API. We’ll use jQuery to make the AJAX calls and also to update the page with the results.

    In Solution Explorer, right-click the project and select Add, then select New Item.

    In the Add New Item dialog, select the Web node under Visual C#, and then select the HTML Page item. Name the page “index.html”.

    Replace everything in this file with the following:


    <br /> Product App<br />

    JSON Web Tokens (JWT) in .NET 6 Web API 🔒 - User Registration / Login / Authentication
    JSON Web Tokens (JWT) in .NET 6 Web API 🔒 - User Registration / Login / Authentication

    Create the ASP.NET Core project

    Create a new solution with a new ASP.NET Core project to migrate to:

    1. Launch a second instance of Visual Studio.
    2. From the File menu, select New > Project.
    3. Select ASP.NET Core Web Application and then select Next.
    4. In the Configure your new project dialog, Name the project WebApp1.
    5. Set the location to a different directory than the previous project to use the same project name. Using the same namespace makes it easier to copy code between the two projects. Select Create.
    6. In the Create a new ASP.NET Core Web Application dialog, confirm that .NET Core and ASP.NET Core 3.1 are selected. Select the Web Application (Model-View-Controller) project template, and select Create.

    Configure the ASP.NET Core site to use MVC

    In ASP.NET Core 3.0 and later projects, .NET Framework is no longer a supported target framework. Your project must target .NET Core. The ASP.NET Core shared framework, which includes MVC, is part of the .NET Core runtime installation. The shared framework is automatically referenced when using the

    Microsoft.NET.Sdk.Web

    SDK in the project file:

    For more information, see Framework reference.

    In ASP.NET Core, the

    Startup

    class:

    • Replaces Global.asax.
    • Handles all app startup tasks.

    For more information, see App startup in ASP.NET Core.

    In the ASP.NET Core project, open the

    Startup.cs

    file:


    public class Startup { public Startup(IConfiguration configuration) { Configuration = configuration; } public IConfiguration Configuration { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddControllersWithViews(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseRouting(); app.UseAuthorization(); app.UseEndpoints(endpoints => { endpoints.MapControllerRoute( name: "default", pattern: "{controller=Home}/{action=Index}/{id?}"); }); } }

    ASP.NET Core apps must opt in to framework features with middleware. The previous template-generated code adds the following services and middleware:

    • The AddControllersWithViews extension method registers MVC service support for controllers, API-related features, and views. For more information on MVC service registration options, see MVC service registration
    • The UseStaticFiles extension method adds the static file handler

      Microsoft.AspNetCore.StaticFiles

      . The

      UseStaticFiles

      extension method must be called before

      UseRouting

      . For more information, see Static files in ASP.NET Core.
    • The UseRouting extension method adds routing. For more information, see Routing in ASP.NET Core.

    This existing configuration includes what is needed to migrate the example ASP.NET MVC project. For more information on ASP.NET Core middleware options, see App startup in ASP.NET Core.

    .NET 7.0 Web API Full course with CRUD actions, Authentication, FileHandling & IIS Deployment - 2023
    .NET 7.0 Web API Full course with CRUD actions, Authentication, FileHandling & IIS Deployment - 2023

    Additional resources

    This article shows how to start migrating an ASP.NET MVC project to ASP.NET Core MVC 2.1. In the process, it highlights many of the things that have changed from ASP.NET MVC. Migrating from ASP.NET MVC is a multi-step process. This article covers:

    • Initial setup
    • Basic controllers and views
    • Static content
    • Client-side dependencies.

    For migrating configuration and Identity code, see Migrate configuration to ASP.NET Core and Migrate Authentication and Identity to ASP.NET Core.

    Note

    The version numbers in the samples might not be current, update the projects accordingly.

    Migrate static content

    In ASP.NET MVC 5 and earlier, static content was hosted from the web project's root directory and was intermixed with server-side files. In ASP.NET Core, static files are stored within the project's web root directory. The default directory is {content root}/wwwroot, but it can be changed. For more information, see Static files in ASP.NET Core.

    Copy the static content from the ASP.NET MVC WebApp1 project to the wwwroot directory in the ASP.NET Core WebApp1 project:

    1. In the ASP.NET Core project, right-click the wwwroot directory, select Add > Existing Item.
    2. In the Add Existing Item dialog, navigate to the ASP.NET MVC WebApp1 project.
    3. Select the favicon.ico file, then select Add, replacing the existing file.
    Project mẫu: ASP.Net Core MVC API
    Project mẫu: ASP.Net Core MVC API

    Create the starter ASP.NET MVC project

    To demonstrate the upgrade, we'll start by creating an ASP.NET MVC app. Create it with the name WebApp1 so the namespace matches the ASP.NET Core project created in the next step.

    Optional: Change the name of the Solution from WebApp1 to Mvc5. Visual Studio displays the new solution name (Mvc5), which makes it easier to tell this project from the next project.

    Create the starter ASP.NET MVC project

    Create an example ASP.NET MVC project in Visual Studio to migrate:

    1. From the File menu, select New > Project.
    2. Select ASP.NET Web Application (.NET Framework) and then select Next.
    3. Name the project WebApp1 so the namespace matches the ASP.NET Core project created in the next step. Select Create.
    4. Select MVC, and then select Create.
    Create Login Page in Asp.net (MVC 5 & SQL Server)
    Create Login Page in Asp.net (MVC 5 & SQL Server)

    Static content

    In ASP.NET MVC 5 and earlier, static content was hosted from the root of the web project and was intermixed with server-side files. In ASP.NET Core, static content is hosted in the wwwroot directory. Copy the static content from the ASP.NET MVC app to the wwwroot directory in the ASP.NET Core project. In this sample conversion:

    • Copy the favicon.ico file from the ASP.NET MVC project to the wwwroot directory in the ASP.NET Core project.

    The ASP.NET MVC project uses Bootstrap for its styling and stores the Bootstrap files in the Content and Scripts directories. The template, which generated the ASP.NET MVC project, references Bootstrap in the layout file (

    Views/Shared/_Layout.cshtml

    ). The

    bootstrap.js

    and

    bootstrap.css

    files could be copied from the ASP.NET MVC project to the wwwroot directory in the new project. Instead, this document adds support for Bootstrap (and other client-side libraries) using CDNs, in the next section.

    See this App Running on Azure

    Would you like to see the finished site running as a live web app? You can deploy a complete version of the app to your Azure account.

    You need an Azure account to deploy this solution to Azure. If you do not already have an account, you have the following options:

    • Open an Azure account for free - You get credits you can use to try out paid Azure services, and even after they're used up you can keep the account and use free Azure services.
    • Activate MSDN subscriber benefits - Your MSDN subscription gives you credits every month that you can use for paid Azure services.
    [NetCore6WebAPI] - 01: Khởi tạo dự án WebAPI trên nền tảng .NET Core 6
    [NetCore6WebAPI] - 01: Khởi tạo dự án WebAPI trên nền tảng .NET Core 6

    Incremental update

    Follow the steps in Get started with incremental ASP.NET to ASP.NET Core migration to continue the update process.

    This article shows how to start migrating an ASP.NET MVC project to ASP.NET Core MVC. In the process, it highlights related changes from ASP.NET MVC.

    Migrating from ASP.NET MVC is a multi-step process. This article covers:

    • Initial setup.
    • Basic controllers and views.
    • Static content.
    • Client-side dependencies.

    For migrating configuration and Identity code, see Migrate configuration to ASP.NET Core and Migrate Authentication and Identity to ASP.NET Core.

    Conclusion

    Thus, the conclusion is always to follow the Restful agreement when working with Web Apis. Api web services are lighter than SOAP-based web services. They have multiple platforms. Restful HTTP verbs are very helpful in the application in inserting, deleting, updating, retrieving records. Here, we see how we use the factor and there are 2 different panels as query header and answer header. Most developers are confused about how to use Web API actions with jquery ajax. Here, we also consume our actions.

    Trong nội dung ở phần trước ta đã thiết lập các phương thức GET,POST,PUT,DELETE và đã test ok trên postman, nay ta sẽ cấu hình Angular để gọi các phương thức đóĐầu tiên hãy mở project củ, và mở thư mục ClientApp, là thư mục Angular của taTạo file comment.model.ts trong thư mục ClientApp/src/app, dùng cấu hình các thuộc tính của comment

    export class Comment { id: number; content: string; parent: number; }

    Tiếp theo ta cần tạo file service chứa các phương thức như GET,POST,PUT,DELETE gọi tới APS MVC 5, các bạn có thể xem các phương thức xử lý service trên trang chủ AngularClientApp/src/app/comment.service.ts

    import { Injectable } from '@angular/core'; import { HttpClient, HttpHeaders, HttpErrorResponse } from '@angular/common/http'; import { Observable, of, throwError } from 'rxjs'; import { map, catchError } from 'rxjs/operators'; import { Comment } from './comment.model'; const httpOptions = { headers: new HttpHeaders({ 'Content-Type': 'application/json', 'X-CSRF-TOKEN': 'QYnhwj1SNxOSgd6wMJi5pxyQJXMgUALjc2Ihv9Si' }) }; @Injectable({ providedIn: 'root', }) export class CommentService { private REST_API_SERVER = 'https://localhost:44332/api'; constructor(private http: HttpClient) { } getAllComment() { return this.http.get(this.REST_API_SERVER + '/comment').pipe(catchError(this.handleError)); } /* * ADD COMMENT * */ postAddComment(comment: Comment): Observable

    { return this.http.post(this.REST_API_SERVER + '/comment', comment, httpOptions).pipe(catchError(this.handleError)); } /** * EDIT COMMENT * */ getComment(id: number) { return this.http.get(this.REST_API_SERVER + '/comment/' + id).pipe(catchError(this.handleError)); } /** * PUT COMMENT (UPDATE COMMENT) * */ putComment(id: number, comment: Comment): Observable

    { return this.http.put(this.REST_API_SERVER + '/comment/' + id, comment, httpOptions).pipe(catchError(this.handleError)); } /** * DELELE COMMENT */ deleteComment(id: number) { return this.http.delete(this.REST_API_SERVER + '/comment/' + id).pipe(catchError(this.handleError)); } handleError(error: HttpErrorResponse) { let errorMessage = 'Unknown error!'; if (error.error instanceof ErrorEvent) { // Client-side errors errorMessage = `Error: ${error.error.message}`; } else { // Server-side errors errorMessage = `Error Code: ${error.status}\nMessage: ${error.message}`; } window.alert(errorMessage); return throwError(errorMessage); } }

    Trong đoạn code file comment.service.ts+ REST_API_SERVER: thông tin URL Project+ Config httpOptions: dùng xử lý request method Post+ handleError: function xử lý lỗi nếu không gọi được APICòn lại các bạn có thể lên search nghiên cứu thêm như(pipe,HttpClient,Observable,..) để hiểu rõ hơnSau khi ta cấu hình file comment.service.ts xong, để sử dụng được ta cần import file vào app.comment.tsClientApp/src/app/app.comment.ts

    import { CommentService } from './comment.service'; constructor(private commentService: CommentService) { }

    File full code app.comment.ts

    import { Component, OnInit } from '@angular/core'; import { CommentService } from './comment.service'; import {Comment} from './comment.model' @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { title = 'Angular + ASP MVC 5'; comments: any; commentAdd: string = ""; commentUpdate: any; checkUpdate = false; constructor(private commentService: CommentService) { } ngOnInit() { this.GetAllComment(); } /*GET COMMENT*/ GetAllComment() { this.commentService.getAllComment().subscribe(item => { this.comments = item; }); } /* * ADD COMMENT */ AddComment() { let _cmt = { "id": 10,//you can set id "content": this.commentAdd, "parent":0,//default 0 } this.commentService.postAddComment(_cmt).subscribe(item => { //IF OK this.comments = item; console.log(item); }); } /* * UPDATE COMMENT */ EditComment(id) { this.checkUpdate = true; this.commentService.getComment(id).subscribe(item => { this.commentUpdate = item; }); } UpdateComment() { let id = this.commentUpdate.id; this.commentService.putComment(id, this.commentUpdate).subscribe(item => { this.comments = item; console.log(item); }); } /* * DELETE COMMENT */ DeleteComment(id: number) { this.commentService.deleteComment(id).subscribe(item => { this.comments = item; console.log(item); }); } }

    Với đoạn code bên trên ta cần thiết lập các tính năng như:(lists comment,add comment,edit,delete)Bạn nào chưa tìm hiểu Angular thì phải tìm hiểu trước nhé, để hình dung ra cách thức hoạt động của đoạn mã trên

    Sau khi ta cấu hình các tính năng trong file app.component.ts xong, ta cần chỉnh giao diện hiển thị tính năng như sau:Mở file app.component.html lên và cấu hình như sau:

    ASP.NET MVC Interview questions and answers on Dependency Injection | ASP.NET Interview Questions
    ASP.NET MVC Interview questions and answers on Dependency Injection | ASP.NET Interview Questions

    Configure the site to use MVC

    • When targeting .NET Core, the Microsoft.AspNetCore.App metapackage is referenced by default. This package contains packages commonly used by MVC apps. If targeting .NET Framework, package references must be listed individually in the project file.


    Microsoft.AspNetCore.Mvc

    is the ASP.NET Core MVC framework.

    Microsoft.AspNetCore.StaticFiles

    is the static file handler. ASP.NET Core apps explicitly opt in for middleware, such as for serving static files. For more information, see Static files.

    • Open the

      Startup.cs

      file and change the code to match the following:


    public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // 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(); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } }

    The UseStaticFiles extension method adds the static file handler. For more information, see Application Startup and Routing.

    Summary

    This article gives an explanation about how to create and access the Web API 2 in the ASP.NET MVC 5 application using C#.

    To download the sample source code please visit the given reference link and download it from there.

    Reference Link

    Introduction

    Today, we'll learn how to access the Web API 2 in the ASP.NET MVC 5 application. Previously we have already learned how to work with the ASP.NET Web API 2.

    Therefore in this article we'll create the Web API and access the Web API using MVC 5.

    So, let's proceed with the following procedure:

    • Create ASP.NET Web API Application
    • Working with Web API Application
    • Working with MVC Controller
    • Adding MVC View

    Prerequisites

    To create this application, there are the following prerequisites:

    • Visual Studio 2013
    • ASP.NET MVC 5

    Create ASP.NET Web API Application

    In this section we'll create the ASP.NET Web Applicaiton using the Web API Project Template. So, start with the following procedure.

    Step 1: Open Visual Studio and click on New Project.

    Step 2: Select the ASP.NET Web Application and enter the name for the application.

    Step 3: Select Web API Project Template and tick the check box of MVC and click OK.

    Visual Studio automatically creates the Web API application using the MVC 5 based projects. When you run the application, the following is the home page of your application.

    You can also click on the Web API option to view the default API structure in the browser. The application Solution Explorer contains all the files and folders associated with the Web API application.

    Working with Web API Application

    Now, we have created the Web API application that uses the MVC 5 based architecture. Now we'll proceed with the following procedure.

    Adding Model

    In this section, we'll add a class and an interface for creating the model. Use the procedure described below.

    Step 1: In the Solution Explorer, right-click on the Models folder and click on Add to add class named Student.

    Step 2: Replace the code with the following code:

    1. using System;
    2. namespace StudentApiApplication.Models
    3. public class Student
    4. public int ID { get; set; }
    5. public string Name { get; set; }
    6. public string City { get; set; }
    7. public string Course { get; set; }

    Step 3: Now add an interface to the models folder named IStudentRepository.

    Step 4: Replace the code with the following code:

    1. using System;
    2. using System.Collections.Generic;
    3. namespace StudentApiApplication.Models
    4. interface IStudentRepository
    5. IEnumerable

      GetAllStudents();
    6. Student AddStudent(Student student);

    Step 5: Now we'll add a repository class in the models folder and after adding it, implement the interface in this class using the following code:

    1. public class StudentRepository : IStudentRepository

    Step 6: Now implement the interface using the following screenshot:

    Now modify the code with the following code:

    1. using System;
    2. using System.Collections.Generic;
    3. namespace StudentApiApplication.Models
    4. public class StudentRepository : IStudentRepository
    5. private List

      items = new List

      ();

    6. private int next = 1;
    7. public StudentRepository()
    8. AddStudent(new Student { ID = 1, Name = "Ashish", City = "New Delhi", Course = "B.Tech" });
    9. AddStudent(new Student { ID = 2, Name = "Nimit", City = "Noida", Course = "MCA" });
    10. AddStudent(new Student { ID = 3, Name = "Prawah", City = "Dehradun", Course = "B.Tech" });
    11. AddStudent(new Student { ID = 4, Name = "Sumit", City = "Nainital", Course = "MCA" });
    12. public IEnumerable

      GetAllStudents()
    13. return items;
    14. public Student AddStudent(Student student)
    15. if (items == null)
    16. throw new ArgumentNullException("student");
    17. student.ID = next++;
    18. items.Add(student);
    19. return student;

    Adding Controller

    So far we have created the model, now we'll create the controller to use the model. Use the following procedure.

    Step 1: In the Solution Explorer, right-click on the Controllers folder and click on Add to add the Controller.

    Step 2: In the Add Scaffold wizard, select the Web API 2 Empty Controller.

    Step 3: Specify the name of the controller.

    Step 4: Replace the code with the following code:

    1. using StudentApiApplication.Models;
    2. using System.Collections.Generic;
    3. using System.Web.Http;
    4. namespace StudentApiApplication.Controllers
    5. public class StudentsController : ApiController
    6. static readonly IStudentRepository studentRepository = new StudentRepository();
    7. public IEnumerable

      GetAll()
    8. return studentRepository.GetAllStudents();

    Working with MVC Controller

    In this section, we'll add an action method to the existing controller. You can also create a new controller. So now open the HomeController.cs in the Controllers folder and modify it with the following code:

    1. using System.Web.Mvc;
    2. namespace StudentApiApplication.Controllers
    3. public class HomeController : Controller
    4. public ActionResult Index()
    5. ViewBag.Title = "Home Page";
    6. return View();
    7. public ActionResult Data()
    8. ViewBag.Title = "Student Details";
    9. return View();

    In the code above, I've added an extra ActionResult method that is returning the View.

    Adding MVC View

    We'll add the MVC view here and work with the newly added view. Use the following procedure.

    Step 1: In the HomeController class, right-click on the Data() and click on Add View.

    Step 2: Enter Data for view name and click on Add.

    Step 3: Replace the code with the following code:

    1. @{
    2. ViewBag.Title = "Data";
    3. C# Web Services Tutorial | Web Services C# Explained | C# Tutorial for Beginners | Simplilearn
      C# Web Services Tutorial | Web Services C# Explained | C# Tutorial for Beginners | Simplilearn

      Upgrade using the .NET Upgrade Assistant

      If your .NET Framework project has supporting libraries in the solution that are required, they should be upgraded to .NET Standard 2.0, if possible. For more information, see Upgrade supporting libraries.

      1. Install the .NET Upgrade Assistant Visual Studio extension.
      2. Open the ASP.NET MVC or Web API solution in Visual Studio.
      3. In Solution Explorer, right click on the project to upgrade and select Upgrade. Select Side-by-side incremental project upgrade, which is the only upgrade option.
      4. For the upgrade target, select New project.
      5. Name the project and select the template. If the project you're migrating is a API project, select ASP.NET Core Web API. If it's an MVC project or MVC and Web API, select ASP.NET Core MVC.
      6. Select Next
      7. Select the target framework version and then select Next. For more information, see .NET and .NET Core Support Policy.
      8. Review the Summary of changes, then select Finish.
      9. The Summary step displays is now connected tovia Yarp proxy. and a pie chart showing the migrated endpoints. Select Upgrade Controller and then select a controller to upgrade.
      10. Select the component to upgrade, then select Upgrade selection.

      Restful Convention

      So, you know what HTTP services and the web API are. Here, we are going to develop an application that supports a few various types of requests.

      GET /API/students (to get the list of students)

      GET /API/students/1 (to get the single student)

      POST /API/students (to add the student and add the students' data in

      Don't confuse GET and POST data requests, we use get request to get a list of resources or data.

      And we use post requests for creating the new one.

      Now, for updating the student, we use the PUT application.

      PUT /API/customers/1

      This way the client id is in the URL and the data or properties to be updated will be in the body of the request. And lastly, remove the student.

      Delete /API/customers/1

      We send the HttpDelete request to the endpoint. So what you see here, in terms of request types and parameters is a standard convention mentioned for requesting REST (Representational State Transfer)

      Read More: Overloading Action Method In Asp.net Mvc

      First, create an ASP.NET Web application project in Visual Studio and call it RestAPI. You can do this by selecting File->New->Project->ASP.NET Web Application and clicking OK.

      After clicking the OK button, the following window would get displayed from where you need to select the Web API and click the OK button.

      Step 2

      We will now build the resource classes below to manage our GET, POST, PUT and DELETE services. Right-click the Templates folder in the Project Explorer window and select Add=>Class(see below).

      Now it would make it easy for you to write actions to the API.

      public IEnumerable

      GetStudents() { }

      Since we return a list of items, this action per convention will reply to.

      // Get /API/students

      So that's the convention embedded in the ASP.Net. Now, in this action, we will use our context to retrieve customers from the database.

      namespace RestAPI.Controllers.API { public class StudentsController: ApiController { private readonly ApplicationDbContext _context; public StudentsController () { _context = new ApplicationDbContext (); } // GET /API/students public IEnumerable

      GetStudents() { Return _context.Students.ToList(); } } }

      If the resource is not found, we return the not found HTTP reply otherwise we return the object.

      // POST /api/students [HttpPost] public Customer CreateStudent(Student student) { }

      This is the client argument that will be in the body of the request and will be automatically initialized by ASP.NET Web API Framework. Now, we should mark that action with HttpPost as we create the resource. And if we follow the naming convention, we don't even need to place the verb action upon action.

      // POST /API/students public Student PostStudent(Student student ) { }

      Initially, however, this is not a good approach. Suppose you refactor the code in the future and rename your action then presumably your code will break. Therefore, you should always use the HTTP verbs at the top of the action.

      Let's now insert the student object into the database with post request of api action.

      // POST /api/students [HttpPost] public Student CreateStudent(Student student) { if (!ModelState.IsValid) { throw new HttpResponseException(HttpStatusCode.BadRequest); } _context.Students.Add(student); _context.SaveChanges(); return student; }

      Another measure: assume we want to update the student.

      // PUT /api/students/1 [HttpPut] public void UpdateStudent(int id, Student student) { if (!ModelState.IsValid) { throw new HttpResponseException(HttpStatusCode.BadRequest); } var studentmgr = _context.Studentd.SingleOrDefault(x => x.Id == id); if (studentmgr == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } studentmgr.Name = student.Name; studentmgr.Std = student.Std; _context.SaveChanges(); }

      Here in this scenario, different people have different views about making the void or the object.

      And if we do the removal action from APIs,

      // Delete /API/students/1 [HttpDelete] public void DeleteStudent(int id) { var stdmr = _context.Students.SingleOrDefault(x => x.ID == id); if (stdmr == null) { throw new HttpResponseException(HttpStatusCode.NotFound); } _context.Students.Remove(stdmr); // Now the object is labeled as deleted in memory. // Now it is done _context.SaveChanges(); }

      Here's how we use the relaxing convention to construct the API.

      How to Consume WEB API in C#  | C# Tutorial for Beginners
      How to Consume WEB API in C# | C# Tutorial for Beginners

      Static content

      In ASP.NET MVC 5 and earlier, static content was hosted from the root of the web project and was intermixed with server-side files. In ASP.NET Core, static content is hosted in the wwwroot directory. Copy the static content from the ASP.NET MVC app to the wwwroot directory in the ASP.NET Core project. In this sample conversion:

      • Copy the favicon.ico file from the ASP.NET MVC project to the wwwroot directory in the ASP.NET Core project.

      The ASP.NET MVC project uses Bootstrap for its styling and stores the Bootstrap files in the Content and Scripts directories. The template, which generated the ASP.NET MVC project, references Bootstrap in the layout file (

      Views/Shared/_Layout.cshtml

      ). The

      bootstrap.js

      and

      bootstrap.css

      files could be copied from the ASP.NET MVC project to the wwwroot directory in the new project. Instead, this document adds support for Bootstrap (and other client-side libraries) using CDNs, in the next section.

      Adding a Model

      A model is an object that represents the data in your application. ASP.NET Web API can automatically serialize your model to JSON, XML, or some other format, and then write the serialized data into the body of the HTTP response message. As long as a client can read the serialization format, it can deserialize the object. Most clients can parse either XML or JSON. Moreover, the client can indicate which format it wants by setting the Accept header in the HTTP request message.

      Let's start by creating a simple model that represents a product.

      If Solution Explorer is not already visible, click the View menu and select Solution Explorer. In Solution Explorer, right-click the Models folder. From the context menu, select Add then select Class.

      Name the class "Product". Add the following properties to the

      Product

      class.


      namespace ProductsApp.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public string Category { get; set; } public decimal Price { get; set; } } }

      Full CRUD Operations | How To Consume WEB API in ASP.NET Core MVC | Consuming Web API
      Full CRUD Operations | How To Consume WEB API in ASP.NET Core MVC | Consuming Web API

      Index

    4. @Html.DisplayName("Name")
    5. @Html.DisplayName("Course")
    6. @Html.DisplayName("City")

    In the code above, I've used the jQuery to call the Web API.

    Step 4: Open the Views/Shared/_Layout.cshtml page and add an ActionLink to redirect to your View.

    1. @Html.ActionLink("Student", "Data", "Home", new { area = "" }, null)

    Step 5: Now run the application. In the Home Page, click on the Student link.

    You can see in the following screenshot that, the data is coming by the Web API.

    Summary

    This article described how to create the Web API and access that Web API in the ASP.NET MVC 5. We'll show the CRUD operations in further articles. Thanks for reading.

    Get Started with ASP.NET Web API 2 (C#)

    by Mike Wasson

    In this tutorial, you will use ASP.NET Web API to create a web API that returns a list of products.

    HTTP is not just for serving up web pages. HTTP is also a powerful platform for building APIs that expose services and data. HTTP is simple, flexible, and ubiquitous. Almost any platform that you can think of has an HTTP library, so HTTP services can reach a broad range of clients, including browsers, mobile devices, and traditional desktop applications.

    ASP.NET Web API is a framework for building web APIs on top of the .NET Framework.

    Test each method

    The layout file and styles have not been migrated yet, so the rendered views only contain the content in the view files. The layout file generated links for the

    About

    and

    Contact

    views will not be available yet.

    Invoke the rendered views from the browser on the running ASP.NET core app by replacing the current port number with the port number used in the ASP.NET core project. For example:

    https://localhost:44375/home/about

    .

    Note the lack of styling and menu items. The styling will be fixed in the next section.

    What is the difference between Web API and MVC Controller?
    What is the difference between Web API and MVC Controller?

    Add a controller and view

    In this section, a minimal controller and view are added to serve as placeholders for the ASP.NET MVC controller and views migrated in the next section.

    • Add a Controllers directory.

    • Add a Controller Class named


      HomeController.cs

      to the Controllers directory.

    • Add a Views directory.

    • Add a Views/Home directory.

    • Add a Razor View named


      Index.cshtml

      to the Views/Home directory.

    The project structure is shown below:

    Replace the contents of the

    Views/Home/Index.cshtml

    file with the following markup:

    Hello world!

    Run the app.

    For more information, see Controllers and Views.

    The following functionality requires migration from the example ASP.NET MVC project to the ASP.NET Core project:

    • client-side content (CSS, fonts, and scripts)

    • controllers

    • views

    • models

    • bundling

    • filters

    • Log in/out, Identity (This is done in the next tutorial.)

    Create the ASP.NET Core project

    Create a new empty ASP.NET Core web app with the same name as the previous project (WebApp1) so the namespaces in the two projects match. Having the same namespace makes it easier to copy code between the two projects. Create this project in a different directory than the previous project to use the same name.

    • Optional: Create a new ASP.NET Core app using the Web Application project template. Name the project WebApp1, and select an authentication option of Individual User Accounts. Rename this app to FullAspNetCore. Creating this project saves time in the conversion. The end result can be viewed in the template-generated code, code can be copied to the conversion project, or compared with the template-generated project.
    Web API CRUD Operations Using Asp Net MVC and Entity Framework
    Web API CRUD Operations Using Asp Net MVC and Entity Framework

    Add a controller and view

    In this section, a minimal controller and view are added to serve as placeholders for the ASP.NET MVC controller and views migrated in the next section.

    • Add a Controllers directory.

    • Add a Controller Class named


      HomeController.cs

      to the Controllers directory.

    • Add a Views directory.

    • Add a Views/Home directory.

    • Add a Razor View named


      Index.cshtml

      to the Views/Home directory.

    The project structure is shown below:

    Replace the contents of the

    Views/Home/Index.cshtml

    file with the following markup:

    Hello world!

    Run the app.

    For more information, see Controllers and Views.

    The following functionality requires migration from the example ASP.NET MVC project to the ASP.NET Core project:

    • client-side content (CSS, fonts, and scripts)

    • controllers

    • views

    • models

    • bundling

    • filters

    • Log in/out, Identity (This is done in the next tutorial.)

    Controllers and views

    • Copy each of the methods from the ASP.NET MVC


      HomeController

      to the new

      HomeController

      . In ASP.NET MVC, the built-in template's controller action method return type is ActionResult; in ASP.NET Core MVC, the action methods return

      IActionResult

      instead.

      ActionResult

      implements

      IActionResult

      , so there's no need to change the return type of the action methods.

    • Copy the


      About.cshtml

      ,

      Contact.cshtml

      , and

      Index.cshtml

      Razor view files from the ASP.NET MVC project to the ASP.NET Core project.

    .NET 5 REST API Tutorial
    .NET 5 REST API Tutorial

    Test each method

    The layout file and styles have not been migrated yet, so the rendered views only contain the content in the view files. The layout file generated links for the

    About

    and

    Contact

    views will not be available yet.

    • Invoke the rendered views from the browser on the running ASP.NET core app by replacing the current port number with the port number used in the ASP.NET core project. For example:

      https://localhost:44375/home/about

      .

    Note the lack of styling and menu items. The styling will be fixed in the next section.

    Search by Employee ID

    Step 9

    Now you have to run your application and for that, you can press F5 and your web page looks as shown below.

    Search Employee By Employee ID

    Step 10

    To View the HTTP Request and Response you have to press F12, and then click on the Network tab and then press start capturing red icon and now go back to the web page and reload the web page or press F5 to reload the web page. You can see the HTTP Request and Response as shown below.

    Bài 11: Triển khai Web API để tạo Resfull API
    Bài 11: Triển khai Web API để tạo Resfull API

    Test each method

    Each controller endpoint can be tested, however, layout and styles are covered later in the document.

    1. Run the ASP.NET Core app.
    2. Invoke the rendered views from the browser on the running ASP.NET Core app by replacing the current port number with the port number used in the ASP.NET Core project. For example,

      https://localhost:44375/home/about

      .

    Solve HTTP 500 errors

    There are many problems that can cause an HTTP 500 error messages that contain no information on the source of the problem. For example, if the

    Views/_ViewImports.cshtml

    file contains a namespace that doesn't exist in the project, a HTTP 500 error is generated. By default in ASP.NET Core apps, the

    UseDeveloperExceptionPage

    extension is added to the

    IApplicationBuilder

    and executed when the configuration is Development. See an example in the following code:


    public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // 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(); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } }

    ASP.NET Core converts unhandled exceptions into HTTP 500 error responses. Normally, error details aren't included in these responses to prevent disclosure of potentially sensitive information about the server. For more information, see Developer Exception Page.

    25 - Consume Web API In ASP.Net MVC | ASP.Net Web API
    25 - Consume Web API In ASP.Net MVC | ASP.Net Web API

    Configure the site to use MVC

    • When targeting .NET Core, the Microsoft.AspNetCore.App metapackage is referenced by default. This package contains packages commonly used by MVC apps. If targeting .NET Framework, package references must be listed individually in the project file.


    Microsoft.AspNetCore.Mvc

    is the ASP.NET Core MVC framework.

    Microsoft.AspNetCore.StaticFiles

    is the static file handler. ASP.NET Core apps explicitly opt in for middleware, such as for serving static files. For more information, see Static files.

    • Open the

      Startup.cs

      file and change the code to match the following:


    public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { services.AddMvc(); } // 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(); } app.UseStaticFiles(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); } }

    The UseStaticFiles extension method adds the static file handler. The

    UseMvc

    extension method adds routing. For more information, see Application Startup and Routing.

    Create the starter ASP.NET MVC project

    To demonstrate the upgrade, we'll start by creating an ASP.NET MVC app. Create it with the name WebApp1 so the namespace matches the ASP.NET Core project created in the next step.

    Optional: Change the name of the Solution from WebApp1 to Mvc5. Visual Studio displays the new solution name (Mvc5), which makes it easier to tell this project from the next project.

    Implementation

    So, let's start with a simple example of the employee where we will retrieve all the information of the employee using WEB API.

    Step 1

    Open Your Visual Studio 2013 or higher versions.

    Step 2

    Go to the File menu and Create New Project same as shown below.

    Step 3

    Now you can see the following popup window on your screen. You have to follow some steps as shown in the screen below.

    Step 4

    Now, when you click on the OK button you can see another popup window will appear on your screen same as shown below, where you have to select WEB API and click OK.

    Step 5

    Finally, your WEB API project has been created and your project structure looks as shown below.

    Step 6

    Now, if you can see, two default created controllers are available where you have to open your controller file "ValuesController.cs" and need to do the following modification in your controller.

    Here, I will change my Controller Name ValueController to EmployeeController which is derived from ApiController.

    1. public class EmployeeController: ApiController

    Now, I will create a simple class and define some basic properties of employees such as ID, Name, Designation, Salary and etc.

    1. public class Employee
    2. public int EmpId { get; set; }
    3. public string EmployeeName { get; set; }
    4. public string Designation { get; set; }
    5. public decimal Salary { get; set; }

    Then I will define a simple array and store some sample data of employees on it.

    1. Employee[] Employees = new Employee[]{
    2. new Employee {EmpId=1,EmployeeName="Nikunj Satasiya", Designation="Software Engineer", Salary=78000},
    3. new Employee {EmpId=2,EmployeeName="Hiren Dobariya", Designation="Software Engineer", Salary=72000},
    4. new Employee {EmpId=3,EmployeeName="Vivek Ghadiya", Designation="Software Engineer", Salary=75000},
    5. new Employee {EmpId=4,EmployeeName="Pratik Pansuriya", Designation="Software Engineer", Salary=55000},
    6. new Employee {EmpId=5,EmployeeName="Nikunj Ladani", Designation="Software Engineer", Salary=42000},
    7. new Employee {EmpId=6,EmployeeName="Sarah Demola", Designation="Software Engineer", Salary=90000}
    8. };

    Now, I will write a method which returns all the details of Employee for every employee.

    1. public IEnumerable

      GetAllEmployees()
    2. return Employees;

    Then I will write a second method which returns details of the single employee based on employee id.

    1. public IHttpActionResult Get(int Id)
    2. var Employee = Employees.FirstOrDefault((e) => e.EmpId == Id);
    3. if (Employee == null)
    4. return NotFound();
    5. return Ok(Employee);

    Step 7

    Now, it's time to add a simple HTML form in our application and for that, you have to follow some steps described on the screen below.

    Step 8

    Now, you have to write the following code in the HTML file.

    HTML Markup

    1. <br /> Codingvila Web API<br />
    2. Phản hồi

      Gửi và xem ý kiến phản hồi dành cho

    In ASP.NET MVC architecture, when the request comes to our application, MVC Framework drops this request to action in a controller, this action returns the view most of the time which is then analyzed by the razor view engine, and finally, the HTML markup is returned to the client. So, HTML tagging is generated on the server and then sent back to the client in this approach.

    Table of Content

    There is another way of generating the HTML tag, we can generate it on the client. This way, instead of sending back HTML tags, they can return raw data.

    Migrate the layout file

    • Copy the


      _ViewStart.cshtml

      file from the ASP.NET MVC project's Views directory into the ASP.NET Core project's Views directory. The

      _ViewStart.cshtml

      file has not changed in ASP.NET Core MVC.

    • Create a Views/Shared directory.

    • Optional: Copy


      _ViewImports.cshtml

      from the FullAspNetCore MVC project's Views directory into the ASP.NET Core project's Views directory. Remove any namespace declaration in the

      _ViewImports.cshtml

      file. The

      _ViewImports.cshtml

      file provides namespaces for all the view files and brings in Tag Helpers. Tag Helpers are used in the new layout file. The

      _ViewImports.cshtml

      file is new for ASP.NET Core.

    • Copy the


      _Layout.cshtml

      file from the ASP.NET MVC project's Views/Shared directory into the ASP.NET Core project's Views/Shared directory.

    Open

    _Layout.cshtml

    file and make the following changes (the completed code is shown below):

    • Replace


      @Styles.Render("~/Content/css")

      with aelement to load

      bootstrap.css

      (see below).

    • Remove


      @Scripts.Render("~/bundles/modernizr")

      .

    • Comment out the


      @Html.Partial("_LoginPartial")

      line (surround the line with

      @*...*@

      ). For more information, see Migrate Authentication and Identity to ASP.NET Core

    • Replace


      @Scripts.Render("~/bundles/jquery")

      with a

      The updated

      _Layout.cshtml

      file is shown below:


      <br /> @ViewBag.Title - My ASP.NET Application<br />

      @Html.ActionLink("Application name", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
      • @Html.ActionLink("Home", "Index", "Home")
      • @Html.ActionLink("About", "About", "Home")
      • @Html.ActionLink("Contact", "Contact", "Home")

      @*@Html.Partial("_LoginPartial")*@

      @RenderBody()

      © @DateTime.Now.Year - My ASP.NET Application

      @RenderSection("scripts", required: false)


      View the site in the browser. It should now load correctly, with the expected styles in place.

      • Optional: Try using the new layout file. Copy the layout file from the FullAspNetCore project. The new layout file uses Tag Helpers and has other improvements.

      Migrate controllers and views

      In the ASP.NET Core project, a new empty controller class and view class would be added to serve as placeholders using the same names as the controller and view classes in any ASP.NET MVC project to migrate from.

      The ASP.NET Core WebApp1 project already includes a minimal example controller and view by the same name as the ASP.NET MVC project. So those will serve as placeholders for the ASP.NET MVC controller and views to be migrated from the ASP.NET MVC WebApp1 project.

      1. Copy the methods from the ASP.NET MVC

        HomeController

        to replace the new ASP.NET Core

        HomeController

        methods. There's no need to change the return type of the action methods. The ASP.NET MVC built-in template's controller action method return type is ActionResult; in ASP.NET Core MVC, the action methods return

        IActionResult

        instead.

        ActionResult

        implements

        IActionResult

        .
      2. In the ASP.NET Core project, right-click the Views/Home directory, select Add > Existing Item.
      3. In the Add Existing Item dialog, navigate to the ASP.NET MVC WebApp1 project's Views/Home directory.
      4. Select the

        About.cshtml

        ,

        Contact.cshtml

        , and

        Index.cshtml

        Razor view files, then select Add, replacing the existing files.

      For more information, see Handle requests with controllers in ASP.NET Core MVC and Views in ASP.NET Core MVC.

      Update Comment




    + Đầu tiên hiển thị danh sách dữ liệu comment+ EditComment(item.id): dùng gọi phương thức edit trong file app.component.ts+ DeleteComment(item.id): xóa dữ liệu tại id nào đó+ AddComment(): gọi phương thức thêm dữ liệu+ checkUpdate: nếu true thì người dùng đang muốn chỉnh sửa , sẽ hiện ra form edit, ngược lại false

    Ok sao đó hãy mở file app.module.ts chỉnh sửa lại như sau:

    import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; @NgModule({ declarations: [ AppComponent ], imports: [ BrowserModule, HttpClientModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

    Ngon lành, giờ ta chỉ cần build nó ra và chạy thử nghiệm thôi, nếu các bạn có xem video Build Angular + ASP MVC 5, thì tại bước này ta cũng build y chang vậyng build --prodSau khi build xong, thì hay run project ASP lên là xong nhé! mọi người có thể làm và phát triển theo ý mình

    Nghiên cứu Web API với ASP.NET MVC4

    Bài đăng này đã không được cập nhật trong 8 năm

    ASP.NET Web API là 1 framework để xây dựng các dịch vụ HTTP có thể truy cập từ nhiều client như trình duyệt hay các thiết bị di động. Web API được giới thiệu là 1 phần của MVC4. Trong bài viết này tôi sẽ giới thiệu thiết kế, khái niệm, tính năng và so sánh Web API với WCF.

    Thực thi 1 WEB API project

    Hãy bắt đầu với việ tạo 1 project ví dụ về Web API. Bước đầu cần tạo 1 ASP.NET MVC 4 project dùng Web API template như hình sau:

    Tiếp đó ta cần tạo 1 Model tên là Product với các thuộc tính như sau:

    Sau khi tạo Product model ta có thể tạo API controller để xử lý Product model:

    Tiếp đó ta tạo 1 số dữ liệu mẫu:


    public class ProductsController : ApiController { List products = new List (); public IEnumerable GetAllProducts() { GetProducts(); return products; } private void GetProducts() { products.Add(new Product {Id = 1, Name = "Television", Category="Electronic", Price=82000}); products.Add(new Product { Id = 2, Name = "Refrigerator", Category = "Electronic", Price = 23000 }); products.Add(new Product { Id = 3, Name = "Mobiles", Category = "Electronic", Price = 20000 }); products.Add(new Product { Id = 4, Name = "Laptops", Category = "Electronic", Price = 45000 }); products.Add(new Product { Id = 5, Name = "iPads", Category = "Electronic", Price = 67000 }); products.Add(new Product { Id = 6, Name = "Toys", Category = "Gift Items", Price = 15000 }); } public IEnumerable GetProducts(int selectedId) { if (products.Count() > 0) { return products.Where(p => p.Id == selectedId); } else { GetProducts(); return products.Where(p => p.Id == selectedId); } }

    Chạy project và thử truy cập API theo 2 url sau ta có thể thấy kết quả như mong đợi:

    http://localhost:11715/api/products

    http://localhost:11715/api/products?selectedID=2

    Truyền những đối tượng phức tạp vào phương thức của Web API:

    Hãy cùng thử 1 ví dụ nếu ta cần truyền 1 object tới phương thức của Web API như sau:


    namespace WebApiProject.Controllers { public class SampleController : ApiController { public string GetTime(Time t) { return string.Format("Received Time: {0}:{1}.{2}", t.Hour, t.Minute, t.Second); } } public class Time { public int Hour { get; set; } public int Minute { get; set; } public int Second { get; set; } } }

    Sau khi chạy thử project truyền vào các tham số Hour, Minute và Second. Ta có thể thấy nó sẽ trả về null exception.




    An error has occurred.


    Object reference not set to an instance of an object.


    System.NullReferenceException


    at WebApiProject.Controllers.SampleController.GetTime(Time t) in c:\Users\Trungx\Documents\Visual Studio 2013\Projects\WebApiProject\WebApiProject\Controllers\SampleController.cs:line 14 at lambda_method(Closure , Object , Object[] ) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.<>c__DisplayClass10.

    b__9(Object instance, Object[] methodParameters) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ActionExecutor.Execute(Object instance, Object[] arguments) at System.Web.Http.Controllers.ReflectedHttpActionDescriptor.ExecuteAsync(HttpControllerContext controllerContext, IDictionary`2 arguments, CancellationToken cancellationToken) --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at System.Web.Http.Controllers.ApiControllerActionInvoker.

    d__0.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at System.Web.Http.Controllers.ActionFilterResult.

    d__2.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at System.Web.Http.Dispatcher.HttpControllerDispatcher.

    d__0.MoveNext()






    Giờ hãy cùng xem sự thay đổi khi ta sửa lại code và thêm thuộc tính [FromUri] để xử lý object truyền vào từ query string:


    public string GetTime([FromUri] Time t)

    Kết quả:



    Received Time: 10:25.12

    Làm việc với HttpClient API:

    Ta có thể gọi đến Web API bằng nhiều cách trong đó có cách sử dụng lớp HttpClient có sẵn của ASP.NET, đoạn code dưới đây giới thiệu cách tạo 1 HttpClient object và dùng nó để truy cập bất đồng bộ đến phương thức API:


    // asynchronous accessing of web api method async Task GetData() { StringBuilder result = new StringBuilder(); // Define the httpClient object using (HttpClient client = new HttpClient()) { // Define the base address of the MVC application hosting the web api // accessing the web api from the same solution client.BaseAddress = new Uri(HttpContext.Current.Request.Url.AbsoluteUri); // Define the serialization used json/xml/ etc client.DefaultRequestHeaders.Accept.Add( new MediaTypeWithQualityHeaderValue("application/json")); // Call the method HttpResponseMessage response = client.GetAsync("api/products").Result; if (response.IsSuccessStatusCode) { // Convert the result into business object var products = response.Content.ReadAsAsync
    >().Result; foreach (var p in products) { result.Append(string.Format("{0} --- [Price: {1} Category: {2}] ", p.Name, p.Price, p.Category)); } } else { result.Append(string.Format("Error Code:-{0} Error Details: {1}", (int)response.StatusCode, response.ReasonPhrase)); } } data.Text = result.ToString(); }

    Truy cập Web API từ jQuery:

    Việc truy cập Web API cũng rất dễ dàng với hàm getJSON:

    Kết quả:


    Television Electronic 82000 Refrigerator Electronic 23000 Mobiles Electronic 20000 Laptops Electronic 45000 iPads Electronic 67000 Toys Gift Items 15000

    Để truyền tham số dùng jQuery ta thêm vào như sau:


    $.getJSON("api/products", { selectedId: '4' }, function (data) { ….});

    Các phương thức Serialization:

    Web API hỗ trợ nhiều phương thức serialization bao gồm: XML, JSON và MessagePack. Trong phần này chúng ta sẽ tìm hiểu cách thực thi 3 phương thức này và so sách cách thể hiện của chúng. Để làm việc đó trước hết hãy sửa project ví dụ của chúng ta trả về 1 lượng dữ liệu để chúng ta hiểu và so sánh hiệu suất của 3 phương thức 1 cách tốt hơn.


    private void GetProducts() { for (int i = 0; i < 5000; i++) { products.Add(new Product { Id = i, Name = "Product - "+i, Category = "The ASP.NET and Visual Web Developer teams have released the ASP.NET and Web Tools 2012.2 update, which extends the existing ASP.NET runtime and adds new web tooling to Visual Studio 2012. Whether you use Web Forms, MVC, Web API, or any other ASP.NET technology, there is something cool in this update for you.", Price = 1 }); } }

    Mặc định Web API dùng JSON là phương thức serialization mặc định. Để dùng XML serialization ta cần chỉnh sửa trong Global.asax thêm vào 2 dòng sau:


    GlobalConfiguration.Configuration.Formatters.RemoveAt(0); GlobalConfiguration.Configuration.Formatters.XmlFormatter.UseXmlSerializer = true;

    Với MessagePack serialization:

    Để dùng phương thức này trước hết ta phải cài đặt MessagePack tại địa chỉ: http://msgpack.org/. Sau khi cài đặt hãy thêm reference thư viện: MsgPack.dll. Tiếp đó tạo 1 MediaTypeFormatter sử dụng MessagePack để serialize.


    public class MediaTypeFormatterCompatibleMessagePack : MediaTypeFormatter { private readonly string _mime = "application/x-msgpack"; Func

    IsAllowedType = (t) => { if (!t.IsAbstract && !t.IsInterface && t != null && !t.IsNotPublic) return true; if (typeof(IEnumerable).IsAssignableFrom(t)) return true; return false; }; public MediaTypeFormatterCompatibleMessagePack() { SupportedMediaTypes.Add(new MediaTypeHeaderValue(_mime)); } public override bool CanWriteType(Type type) { if (type == null) throw new ArgumentNullException("Type is null"); return IsAllowedType(type); } public override Task WriteToStreamAsync(Type type, object value, System.IO.Stream stream, HttpContent content, TransportContext transportContext) { if (type == null) throw new ArgumentNullException("type is null"); if (stream == null) throw new ArgumentNullException("Write stream is null"); var tcs = new TaskCompletionSource
    (); if (type != typeof(string) && typeof(IEnumerable).IsAssignableFrom(type)) { value = (value as IEnumerable
    ).ToList(); } var serializer = MessagePackSerializer.Create

    (); serializer.Pack(stream, value); tcs.SetResult(null); return tcs.Task; } public override Task
    ReadFromStreamAsync(Type type,Stream stream, HttpContent content, IFormatterLogger formatterLogger) { var tcs = new TaskCompletionSource
    (); if (content.Headers != null && content.Headers.ContentLength == 0) return null; try { var serializer = MessagePackSerializer.Create(type); object result; using (var mpUnpacker = Unpacker.Create(stream)) { mpUnpacker.Read(); result = serializer.UnpackFrom(mpUnpacker); } tcs.SetResult(result); } catch (Exception e) { if (formatterLogger == null) throw; formatterLogger.LogError(String.Empty, e.Message); tcs.SetResult(GetDefaultValueForType(type)); } return tcs.Task; } public override bool CanReadType(Type type) { if (type == null) throw new ArgumentNullException("type is null"); return IsAllowedType(type); } }



    Tiếp đó ta cấu hình trong Global.asax tương tự như với phương thức XML:


    GlobalConfiguration.Configuration.Formatters.Clear(); GlobalConfiguration.Configuration.Formatters.Add(new MediaTypeFormatterCompatibleMessagePack());

    So sánh 3 phương thức ta thu được kết quả về khả năng nén dữ liệu: MessagePack > JSON > XML

    WCF và Web API:

    Tất nhiên WCF hỗ trợ rất nhiều giao thức trong đó có cả HTTP tuy nhiên để thực thi 1 service dựa trên HTTP bằng WCF khá khó khăn và phức tạp và không sử dụng được các tính năng chính của HTTP như Caching hay Status Code. Trong khi đó sử dụng WEB API ta có thể thực thi tất cả GET,POST,PUT,DELETE và đầy đủ các tính năng của HTTP 1 cách dễ dàng.

    All rights reserved

    Keywords searched by users: web api in mvc 5

    (#70) Web API in MVC 5 project | mvc tutorial for beginners in .net c# | MVC By Nitish
    70) Web Api In Mvc 5 Project | Mvc Tutorial For Beginners In .Net C# | Mvc By Nitish - Youtube
    Consuming A Web Api Asynchronously In Asp.Net Mvc Or Wpf | Dotnetcurry
    Consuming A Web Api Asynchronously In Asp.Net Mvc Or Wpf | Dotnetcurry
    Creating Asp.Net Web Api With Mvc 6 | Dotnetcurry
    Creating Asp.Net Web Api With Mvc 6 | Dotnetcurry
    Filter Pipeline In Web Api Part 1 | Asp.Net Core 5 Web Api - Ep 4 | Rest Api  | Mvc Filters - Youtube
    Filter Pipeline In Web Api Part 1 | Asp.Net Core 5 Web Api - Ep 4 | Rest Api | Mvc Filters - Youtube
    Tutorial: Create A Web Api With Asp.Net Core | Microsoft Learn
    Tutorial: Create A Web Api With Asp.Net Core | Microsoft Learn
    70) Web Api In Mvc 5 Project | Mvc Tutorial For Beginners In .Net C# | Mvc  By Nitish - Youtube
    70) Web Api In Mvc 5 Project | Mvc Tutorial For Beginners In .Net C# | Mvc By Nitish - Youtube
    Tutorial: Create A Web Api With Asp.Net Core | Microsoft Learn
    Tutorial: Create A Web Api With Asp.Net Core | Microsoft Learn
    Khai Giảng Khóa Học Lập Trình Web Với Công Nghệ Asp.Net Mvc 5 / Webapi /  Angularjs | Devmaster
    Khai Giảng Khóa Học Lập Trình Web Với Công Nghệ Asp.Net Mvc 5 / Webapi / Angularjs | Devmaster
    Get Data In Asp.Net Mvc Using Web Api
    Get Data In Asp.Net Mvc Using Web Api
    70) Web Api In Mvc 5 Project | Mvc Tutorial For Beginners In .Net C# | Mvc  By Nitish - Youtube
    70) Web Api In Mvc 5 Project | Mvc Tutorial For Beginners In .Net C# | Mvc By Nitish - Youtube
    Build Web Api Using Angular With Asp.Net Mvc5 (Part 1)
    Build Web Api Using Angular With Asp.Net Mvc5 (Part 1)
    Build Web Api Using Angular With Asp.Net Mvc 5 (Part 2)
    Build Web Api Using Angular With Asp.Net Mvc 5 (Part 2)

    See more here: kientrucannam.vn

    Trả lời

    Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *