Chuyển tới nội dung
Home » Wcf To Web Api | Fast, Native Implementation

Wcf To Web Api | Fast, Native Implementation

WCF vs Web API | ASP.NET WebAPI Tutorial

WCF Rest

To use WCF as WCF Rest service you have to enable webHttpBindings. It supports HTTP GET and POST verbs by [WebGet] and [WebInvoke] attributes respectively. To enable other HTTP verbs you have to do some configuration in IIS to accept requests of that particular verb on .svc files. Passing data through parameters using a WebGet needs configuration. The UriTemplate must be specified. It supports XML, JSON, and ATOM data formats.

Fast, Native Implementation

Visual ReCode works by moving your source code from a .NET Framework project to a new .NET Core project and rewriting it as a native ASP.NET Core Web API. It doesn’t add any proprietary third party libraries – instead it creates the same code you would make yourself if you were starting from scratch today.

Once you’ve ReCoded your application you don’t need Visual ReCode around to compile it, modify it, or deploy – because everything’s using the native .NET Core implementations just like a brand new implementation.

MigrateWcfToWebApi

.NET Core console app that auto generates ASP.NET Web API service and associated client code files to replace exising WCF Service endpoints.

Roslyn (.NET Compiler Platform) libraries for C# are used to parse/generate the files.

WCF vs Web API | ASP.NET WebAPI Tutorial
WCF vs Web API | ASP.NET WebAPI Tutorial

The deciding factor for WCFWeb API

Following is a quick checklist to help to determine whether to use WCF or Web API

Scenario WCF 4.5 ASP.NET Web API
Requires support for scenarios like Message queues, end to end message security, duplex communication, distributed transactions, etc. Select Do NOT Select
When you already have existing working WCF services and Wants to add HTTP support additionally. Select Do NOT Select
One code base to provide support both SOAP and RESTful endpoints. Select Do NOT Select
Wants to create a resource-oriented service over HTTP. Do NOT Select Select
Your project is an MVC application and wants some functionality over HTTP. Do NOT Select Select
You want to build only an HTTP / RESTful services Do NOT Select Select

18

feb.

Difference between WCF and Web API and WCF REST and Web Service

KEY DIFFERENCE

  • WCF offers request-reply, one-way, or duplex while Web API is by default request-reply only.
  • WCF is used for developing SOAP-based services whereas Web API is used for both SOAP-based and RESTful services.
  • WCF does not offer any support for MVC features whereas Web API supports MVC features.
  • WCF supports HTTP, UDP, and custom transport protocol whereas Web API supports only HTTP protocol.
  • WCF offers Text, MTOM, and Binary Encoding support whereas Web API supports the UTF-8 encoding format.
  • WCF supports message queues, message security, duplex communication, transaction whereas Web API doesn’t support.
  • WCF stands for Windows Communication Foundation whereas API stands for Application Program Interface.
WCF vs WebApi
WCF vs WebApi

Choosing which technology to use

The following table describes the major features of each technology.

WCF ASP.NET Web API
Enables building services that support multiple transport protocols (HTTP, TCP, UDP, and custom transports) and allows switching between them. HTTP only. First-class programming model for HTTP. More suitable for access from various browsers, mobile devices etc enabling wide reach.
Enables building services that support multiple encodings (Text, MTOM, and Binary) of the same message type and allows switching between them. Enables building Web APIs that support wide variety of media types including XML, JSON etc.
Supports building services with WS-* standards like Reliable Messaging, Transactions, Message Security. Uses basic protocol and formats such as HTTP, WebSockets, SSL, JSON, and XML. There is no support for higher level protocols such as Reliable Messaging or Transactions.
Supports Request-Reply, One Way, and Duplex message exchange patterns. HTTP is request/response but additional patterns can be supported through SignalR and WebSockets integration.
WCF SOAP services can be described in WSDL allowing automated tools to generate client proxies even for services with complex schemas. There is a variety of ways to describe a Web API ranging from auto-generated HTML help page describing snippets to structured metadata for OData integrated APIs.
Ships with the .NET Framework. Ships with .NET Framework but is open-source and is also available out-of-band as independent download.

Use WCF to create reliable, secure web services that are accessible over a variety of transports. Use ASP.NET Web API to create HTTP-based services that are accessible from a wide variety of clients. Use ASP.NET Web API if you are creating and designing new REST-style services. Although WCF provides some support for writing REST-style services, the support for REST in ASP.NET Web API is more complete and all future REST feature improvements will be made in ASP.NET Web API. If you have an existing WCF service and you want to expose additional REST endpoints, use WCF and the WebHttpBinding.

How To Migrate From WCF Service To ASP .NET Core Web API (REST)?

For more than ten years, Windows Communication Foundation (WCF) has been a well-liked framework for creating service-oriented applications. To increase performance, scalability, and maintainability nevertheless, it is becoming more and more crucial to switch from WCF to newer technologies like ASP .NET Core Web API (REST). This blog post offers a detailed tutorial for switching from WCF to the ASP .NET Core Web API.

ReCode from WCF to ASP.NET Core MVC

If you want to migrate to a modern micro-services approach you can convert your WCF applications to use
a native HTTP API – built with ASP.NET Core. Visual ReCode will guide you through creating a new
.NET Core 3.1 Web API Project and then automatically copy and rewrite your existing

ServiceContract

types and implementations
into ASP.NET Core Web API Controllers.

Of course, just converting the controllers doesn’t cover all your application does – so ReCode will also
create POCO data transfer objects from

DataContract

types and identify and copy dependencies from your
WCF project(s) to .NET Core 3.1 project(s). You can chose to merge or split your service contracts between
multiple projects to optimize how you want your final application code structure to be.

Top 20 Interview Questions - Web API - .NET C#
Top 20 Interview Questions – Web API – .NET C#

Sự khác nhau giữa Web Service, WCF, WCF REST, Web API

Giới thiệu

Hiện nay trong kỷ nguyên hậu PC, smartphone và tablet lên ngôi, nhu cầu xây dựng các ứng dụng mobile trên Windows Phone, iOS, Android đồng bộ dữ liệu đến server theo mô hình điện toán đám mây đang trở nên rất hot. Nếu quyết định xây dựng phía server sử dụng .NET Framework (với phiên bản mới nhất 4.5.3) thì lập trình viên có thể tạo ra các HTTP service bằng rất nhiều công nghệ khác nhau như là:- Web service (ASMX)- WCF service- WCF REST service- Web API serviceĐiều này rất tốt vì nó cho phép lập trình viên có nhiều lựa chọn hơn trong việc xây dựng các HTTP service dựa trên nền .NET nhưng với những người mới tiếp cận .NET Framework sẽ rối không biết cần phải sử dụng công nghệ nào để bắt đầu. Trong bài viết này chúng ta sẽ cùng điểm qua các công nghệ này để thấy được sự khác nhau giữa chúng từ đó có một cái nhìn toàn diện nhất về các công nghệ service trên .NET đồng thời quyết định được công nghệ nào là phù hợp nhất với nhu cầu của mình.

Ưu điểm:

– Bổ sung hỗ trợ RESTful service với định dạng dữ liệu JSON nhẹ hơn SOAP với dữ liệu XML rất nhiều- Cho phép cấu hình tham số WebGet qua URI sử dụng UriTemplate

Nhược điểm:

– Chưa hoàn toàn phải là RESTful service, mới chỉ hỗ trợ mặc định GET, POST- Cấu hình khó nhớ (cố hữu của WCF)

Web API (.NET 4 trở lên)

– Đây là một framework mới giúp cho việc xây dựng các HTTP service rất đơn giản và nhanh chóng- Open Source và có thể được sử dụng bởi bất kì client nào hỗ trợ XML, JSON- Hỗ trợ đầy đủ các thành phần HTTP: URI, request/response headers, caching, versioning, content formats- Có thể host trong ứng dụng hoặc trên IIS- Kiến trúc lý tưởng cho các thiết bị có băng thông giới hạn như smartphone, tablet- Định dạng dữ liệu có thể là JSON, XML hoặc một kiểu dữ liệu bất kỳ

Ưu điểm:

– Cấu hình hết sức đơn giản khi so với WCF- Performance cao- Hỗ trợ RESTful đầy đủ- Hỗ trợ đầy đủ các thành phần MVC như: routing, controller, action result, filter, model binder, IoC container, dependency injection, unit test- Open Source

Nhược điểm:

– Còn rất mới nên chưa có nhiều đánh giá về nhược điểm của Web API

Vậy tôi nên lựa chọn framework nào để phát triển HTTP Service?

Câu trả lời sẽ tùy thuộc vào yêu cầu công việc cụ thể của bạn như thế nào?Web Service:- Lựa chọn khi bạn chỉ cần xây dựng một service đơn giảnWCF là lựa chọn số một khi xây dựng:- Service cần hỗ trợ những ngữ cảnh đặc biệt như: message queue, duplex communication…- Service sử dụng những kênh truyền dữ liệu ở tầng thấp cho nhanh như: TCP, Named Pipes, UDP…WCF Rest, Web API được sử dụng khi xây dựng:- Service RESTful hỗ trợ đầy đủ các thành phần HTTP: URI, request/response headers, caching, versioning, content formats- Service cung cấp dữ liệu cho nhiều client khác nhau với băng thông giới hạn như: browser, mobile, tablet…

Kết luận

Qua bài viết này chúng ta đã có một cái nhìn tổng quan hơn về 4 công nghệ hỗ trợ tạo HTTP service trên nền tảng .NET: Web Service, WCF, WCF REST, Web API. Với sự phát triển vũ bão của các thiết bị smartphone, tablet như hiện nay các công nghệ WCF REST và mới đây nhất là WEB API đang nổi lên là những công nghệ lý tưởng nhất cho việc xây dựng các ứng dụng điện toán đám mây. Việc nắm bắt được các công nghệ này là nhu cầu cấp thiết của các lập trình viên vì vậy trong các bài viết sau chúng ta sẽ cùng tìm hiểu chi tiết về cách tạo và sử dụng các service này.

BTV.Trần Thị Thu HuyềnPhòng Truyền Thông IMicroSoft Việt NamHotline: 0916 878 224Email: [email protected]

Bạn đang muốn tìm kiếm 1 công việc với mức thu nhập cao.✅ Hoặc là bạn đang muốn chuyển đổi công việc mà chưa biết theo học ngành nghề gì cho tốt.✅ Giới thiệu với bạn Chương trình đào tạo nhân sự dài hạn trong 12 tháng với những điều đặc biệt mà chỉ có tại IMIC và đây cũng chính là sự lựa chọn phù hợp nhất dành cho bạn:👉 Thứ nhất: Học viên được đào tạo bài bản kỹ năng, kiến thức chuyên môn lý thuyết, thực hành, thực chiến nhiều dự án và chia sẻ những kinh nghiệm thực tế từ Chuyên gia có nhiều năm kinh nghiệm dự án cũng như tâm huyết truyền nghề.👉 Thứ hai: Được ký hợp đồng cam kết chất lượng đào tạo cũng như mức lương sau tốt nghiệp và đi làm tại các đối tác tuyển dụng của IMIC. Trả lại học phí nếu không đúng những gì đã ký kết.👉 Thứ ba: Cam kết hỗ trợ giới thiệu công việc sang đối tác tuyển dụng trong vòng 10 năm liên tục.👉 Thứ tư: Được hỗ trợ tài chính với mức lãi suất 0 đồng qua ngân hàng VIB Bank.👉 Có 4 Chương trình đào tạo nhân sự dài hạn dành cho bạn lựa chọn theo học. Gồm có:1) Data Scientist full-stack2) Embedded System & IoT development full-stack3) Game development full-stack4) Web development full-stack✅ Cảm ơn bạn đã dành thời gian lắng nghe những chia sẻ của mình. Và tuyệt vời hơn nữa nếu IMIC được góp phần vào sự thành công của bạn.✅ Hãy liên hệ ngay với Phòng tư vấn tuyển sinh để được hỗ trợ về thủ tục nhập học.✅ Chúc bạn luôn có nhiều sức khỏe và thành công!

In Development

Migrate WCF to ASP.NET Core MVC

Why used Web API?

Here, are pros/benefits of using web API:

  • Web API provides supports for convention-based CRUD Actions since it works with HTTP verbs ( GET, PUT, POST, and DELETE)
  • It is easy to define, expose, and consume in a REST-ful way.
  • ASP.Net Web API allows you to showcase your data and services to various devices.
  • Web API is open source, so it is an ideal option for creating RESTful services over the .NET platform.
  • Allows you scalable, decoupled development of a Web Service which can be shared and used by other developers to access web services.
  • It is also helpful to build simple, non-SOAP-based HTTP Services.
C# WCF Client/Server App in Visual Studio 2019
C# WCF Client/Server App in Visual Studio 2019

Add OpenAPI Metadata

HTTP APIs aren’t documented in the same way WCF SOAP APIs are; there’s no

WSDL

metadata for generating
client code. The modern alternative to this is OpenAPI
(formerly known as “Swagger”), which provides interactive documentation of your APIs in the browser and
supports client code generation across multiple platforms. Visual ReCode can automatically add the necessary
code to support OpenAPI as it migrates your WCF application to ASP.NET Core Web API. By using the
[NSwag]

In Development

We are working on support for migrating WCF SOAP services to modern HTTP APIs with ASP.NET Core MVC.

Like our WCF to gRPC support, the generated code will follow best practices, including OpenAPI for documenting APIs and generating client code for multiple platforms and languages. Again, no proprietary packages or runtime dependencies will be added; once you’ve ReCoded your application, it’s all yours.

What is ASP NET Web API
What is ASP NET Web API

Choosing which technology to use

The following table describes the major features of each technology.

WCF ASP.NET Web API
Enables building services that support multiple transport protocols (HTTP, TCP, UDP, and custom transports) and allows switching between them. HTTP only. First-class programming model for HTTP. More suitable for access from various browsers, mobile devices etc enabling wide reach.
Enables building services that support multiple encodings (Text, MTOM, and Binary) of the same message type and allows switching between them. Enables building Web APIs that support wide variety of media types including XML, JSON etc.
Supports building services with WS-* standards like Reliable Messaging, Transactions, Message Security. Uses basic protocol and formats such as HTTP, WebSockets, SSL, JSON, and XML. There is no support for higher level protocols such as Reliable Messaging or Transactions.
Supports Request-Reply, One Way, and Duplex message exchange patterns. HTTP is request/response but additional patterns can be supported through SignalR and WebSockets integration.
WCF SOAP services can be described in WSDL allowing automated tools to generate client proxies even for services with complex schemas. There is a variety of ways to describe a Web API ranging from auto-generated HTML help page describing snippets to structured metadata for OData integrated APIs.
Ships with the .NET Framework. Ships with .NET Framework but is open-source and is also available out-of-band as independent download.

Use WCF to create reliable, secure web services that are accessible over a variety of transports. Use ASP.NET Web API to create HTTP-based services that are accessible from a wide variety of clients. Use ASP.NET Web API if you are creating and designing new REST-style services. Although WCF provides some support for writing REST-style services, the support for REST in ASP.NET Web API is more complete and all future REST feature improvements will be made in ASP.NET Web API. If you have an existing WCF service and you want to expose additional REST endpoints, use WCF and the WebHttpBinding.

I have inherited a legacy .NET WCF service. It is currently hosted within an ASP.NET application.

I need to extract this into a separate ASP.NET Web API 2 service. I want to get rid of the WCF service altogether instead of simply wrapping it with the Web API.

I know that if I was using .NET Core it would be a much simpler as I could used Swagger.

Unfortunately this not an option as we are using the standard .NET framework.

I’m using Visual Studio 2019 and using the available templates to create the service framework.

I am running into difficulty creating the correct routing tags. I assume my method calls would be mapped to action verbs.

Here is a sample code block reflecting what my

svc.cs

file contains:


using System; using System.Linq; using System.ServiceModel.Activation; [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class SampleService : ISampleService { public Result1 ServiceCallA(string param1, SampleClass1 param2, SampleClass2 param3) {} public Result1 ServiceCallB(string param1, string param2, bool param3) {} public Result2 ServiceCallC(string param1, string param2) {} public Result2 ServiceCallD(string param1) {} }

Here is a sample block with my Web API definitions:


using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; public class ClientActivationController : ApiController { [HttpGet] [Route("???")] public Result1 ServiceCallA(string param1, SampleClass1 param2, SampleClass2 param3) {} [HttpGet] [Route("???")] public Result1 ServiceCallB(string param1, string param2, bool param3) {} [HttpGet] [Route("???")] public Result2 ServiceCallC(string param1, string param2) {} [HttpGet] [Route("???")] public Result2 ServiceCallD(string param1) {} }

Here is the standard boilerplate template startup code:


public class WebApiApplication : System.Web.HttpApplication { protected void Application_Start() { GlobalConfiguration.Configure(WebApiConfig.Register); } } public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{id}", defaults: new { id = RouteParameter.Optional } ); } }

I would like to use the

HttpClient

to access the services from my Winforms apps.

I am not entirely clear how to construct the URL with embedded parameters.

Here is a code snippet for consuming the service:


var uri = new Uri($"{ServiceUrl}/ServiceCallA ?????"); var response = await _client.GetAsync(uri); if (response.IsSuccessStatusCode) { return Ok(response.Content.ReadAsStringAsync().Result); } else { return StatusCode(500, "Server error"); }

WCF Vs Web Service

Parameter WCF Web API
Message Exchange Pattern Request reply, one-way, or duplex. By default request-reply only. However, additional message pattern can be supported with web sockets integration.
Hosting IIS hosting, Self-hosting & works activation services. Self-hosting & IIS hosting.
Open Source It is not open source software. It is shipped with.Net framework.It is also available as an independent download.
Support for MVC features WCF does not provide any support for MVC features like controllers, routing, filter, auction results, etc. ASP.NET Web API supports MVC features like routing, controllers, results, filter, action, etc.
Encoding support Text, MTOM, and Binary. Default support for UTF-8 encoding format.
Support for Support for HTTP, UDP, and custom transport protocol. Supports only HTTP protocol
Use of model User attributed based programming model. Maps HTTP verbs to methods
Configuration Uses web.config and attributes to configure a HttpConfiguration class but not on the web.config Service. Web API can be configured using web.config service.
RESTful services It offers supports for RESTFUL service but with limitations. Ideal for building RESTFUL services.
[WebAPI-NET5] #1 - Tạo API đầu tiên
[WebAPI-NET5] #1 – Tạo API đầu tiên

Difference between WCF and Web API and WCF REST and Web Service

Feature WCF Web API WCF REST Web Services (ASMX)
Purpose General-purpose service framework Building HTTP services (RESTful) RESTful services over WCF Building SOAP-based services
Communication SOAP, REST, one-way, duplex RESTful (HTTP) RESTful (HTTP) SOAP (HTTP)
Hosting IIS, self-hosting, WAS IIS, self-hosting IIS, self-hosting, WAS IIS
Programming model Contract-based, attributes MVC-based Contract-based, attributes Contract-based
Data format XML, JSON, binary JSON, XML, and other formats JSON, XML XML
Security WS-Security, message security HTTP-based security HTTP-based security WS-Security
Extensibility Custom bindings, behaviors Middleware, filters Custom bindings, behaviors Limited
Ideal for Enterprise-level services, interoperability Modern web, mobile, and cloud apps RESTful services within WCF Legacy systems, interoperability
Summary

Web Services (SOAP), WCF (flexible but complex), WCF REST (limited REST support), and Web API (modern, RESTful, open-source) are all alternatives for implementing HTTP services in the .NET framework. Web API is appropriate for modern programs, WCF/REST for certain circumstances, and Web Services for legacy systems. Each choice has advantages and disadvantages, so choose cautiously based on your requirements.

Web API

This is the new framework for building HTTP services easily and simply. Web API is open source an ideal platform for building RESTful services over the .NET Framework. Unlike the WCF Rest service, it uses the full features of HTTP (like URIs, request/response headers, caching, versioning, and various content formats). It also supports the MVC features such as routing, controllers, action results, filter, model binders, IOC container or dependency injection, and unit testing makes it more simple and robust. It can be hosted within the application or on IIS. It is lightweight architecture and good for devices that have limited bandwidth like smartphones. Responses are formatted by Web API’s MediaTypeFormatter into JSON, XML, or whatever format you want to add as a MediaTypeFormatter.

[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

Step-by-Step Guide to Migrate from WCF to ASP .NET Core Web API

Here are the steps you can follow to migrate from WCF to ASP .NET Core Web API:

Step 1: Identify the Services to be Migrated

Finding the WCF services that need to be migrated is the first step. Services that are essential to your application and those that need regular upgrades or maintenance should be given top priority.

Step 2: Create an ASP .NET Core Web API Project

The following action is to start a fresh Visual Studio ASP .NET Core Web API project. To achieve this, use the “API” project type after choosing the “ASP .NET Core Web Application” template.

Step 3: Add Required NuGet Packages

Once you have created the Web API project, you need to add the required NuGet packages for building RESTful services. Some of the key packages you will need include:

You can add these packages by right-clicking on the project in the Solution Explorer and selecting “Manage NuGet Packages.”

Step 4: Define Models and Controllers

The models and controllers for your Web API service must be defined next. You may accomplish this by declaring the corresponding controllers after establishing new classes for your models.

You can provide the HTTP methods (GET, POST, PUT, DELETE, etc.) and the associated actions that will be taken when these methods are invoked in the controllers.

Step 5: Implement Dependency Injection

A crucial component of ASP .NET Core is dependency injection, which is used to handle dependencies across the various parts of your application. By developing a Startup class and then specifying the necessary services in the ConfigureServices function, dependency injection may be implemented.

Step 6: Configure Authentication and Authorization

Any RESTful service must have authentication and permission, and ASP .NET Core offers numerous ways to implement these functionalities. JSON Web Tokens (JWT) are a popular method for authentication and authorization.

Adding the necessary middleware to your Startup class, then defining the authentication and authorization options, are how you establish authentication and authorization.

Step 7: Test and Debug the Web API Service

Once the implementation is complete, you may test and debug the Web API service with tools like Postman or Swagger. Visual Studio may also be used to troubleshoot the service and inspect the logs.

Step 8: Deploy

The final step is to put the Web API service into production. The service may be deployed on a variety of platforms, including Azure, AWS, and a self-hosted server.

When launching the service, make sure that adequate security measures are in place to secure your data and prevent unwanted access.

Code Examples

Here are some code examples that illustrate how to migrate from WCF to ASP .NET Core Web API.

Defining a Model in Web API

In Web API, you can define models using plain C# classes. For example, to define a “Customer” model, you can create a new class like this:

public class Customer { public int Id { get; set; } public string Name { get; set; } public string Email { get; set; } public string Phone { get; set; } }

Defining a Controller in Web API

In Web API, you can define controllers using the “ApiController” attribute. For example, to define a “Customers” controller, you can create a new class like this:

[ApiController] [Route(“api/[controller]”)] public class CustomersController : ControllerBase { private readonly ICustomerService _customerService; public CustomersController(ICustomerService customerService) { _customerService = customerService; } [HttpGet] public async Task

>> Get() { var customers = await _customerService.GetCustomersAsync(); return Ok(customers); } [HttpGet(“{id}”)] public async Task

> Get(int id) { var customer = await _customerService.GetCustomerAsync(id); if (customer == null) { return NotFound(); } return Ok(customer); } [HttpPost] public async Task

> Post(Customer customer) { await _customerService.AddCustomerAsync(customer); return CreatedAtAction(nameof(Get), new { id = customer.Id }, customer); } [HttpPut(“{id}”)] public async Task

Put(int id, Customer customer) { if (id != customer.Id) { return BadRequest(); } await _customerService.UpdateCustomerAsync(customer); return NoContent(); } [HttpDelete(“{id}”)] public async Task

Delete(int id) { await _customerService.DeleteCustomerAsync(id); return NoContent(); } }




Implementing Dependency Injection in Web API

In Web API, you can implement dependency injection using the “IServiceCollection” interface. For example, to configure the “ICustomerService” interface, you can add the following code to the “ConfigureServices” method in your Startup class:

public void ConfigureServices(IServiceCollection services) { services.AddScoped

(); }

Configuring Authentication and Authorization in Web API

In Web API, you can configure authentication and authorization using the “AddAuthentication” and “AddAuthorization” methods in your Startup class. For example, to configure JWT authentication and authorization, you can add the following code to the “ConfigureServices” method:

public void ConfigureServices(IServiceCollection services) { // … services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.RequireHttpsMetadata = false; options.SaveToken = true; options.TokenValidationParameters = new TokenValidationParameters { ValidateIssuerSigningKey = true, IssuerSigningKey = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(Configuration[“Jwt:Key”])), ValidateIssuer = false, ValidateAudience = false }; }); services.AddAuthorization(options => { options.AddPolicy(“AdminOnly”, policy => policy.RequireRole(“admin”)); }); }

In the above code, we have defined a policy named “AdminOnly” that requires the user to have the “admin” role to access the resource.

Calling a Web API Service from a Client

To call a Web API service from a client, you can use any HTTP client library that supports sending requests and receiving responses.

Here’s an example of calling the “Get” method of the “Customers” controller using the HttpClient class:

var httpClient = new HttpClient(); var response = await httpClient.GetAsync(“https://localhost:5001/api/customers”); var customers = await response.Content.ReadAsAsync >();

In the above code, we have created a new instance of the HttpClient class and used it to send a GET request to the “https://localhost:5001/api/customers” endpoint. We then read the response content as a list of Customer objects.

Why You Need To Upgrade

The most recent version of .NET platform is .NET 6, built off of .NET Core. While some .NET Framework technologies were ported over, WCF was not one of them, and there are no plans to change that. This means developers who continue to use WCF are stuck using a version of .NET that is no longer being innovated. Using the best version of .NET possible requires a switch.

Even if it were, it would not be the right solution for modern API development.

WCF was originally released as part of .NET Framework 3.0 at the end of 2006. The world of distributed systems was very different then: JSON was barely a thing, and Remote Procedure Calls (RPC) using XML-serialized SOAP messages was the prevailing standard for Service Oriented Architectures. The term “microservices” would not be coined for another five years. And technology moves forward ever-faster, so in the years since WCF was conceived, people have come up with better solutions to the problems it sought to solve.

Where does that leave you and many others that have a deep investment in WCF for building your critical applications?

[WebAPI-NET5] #8 Secure API with Json Web Token (JWT)
[WebAPI-NET5] #8 Secure API with Json Web Token (JWT)

Why use WCF?

Here, are pros/benefits of using WCF:

  • WCF is an ideal option if you are planning to use .NET Framework 3.5.
  • WCF support multiple protocols such as HTTP, TCP, Named pipe.
  • WCF service is useful if you want to build service with standards like Transactions Messaging security and Reliable Message Security.
  • You can use Request-Reply, One Way, and Duplex message exchange patterns with WCF.

WCF

It is also based on SOAP and returns data in XML form. It is the evolution of the web service(ASMX) and supports various protocols like TCP, HTTP, HTTPS, Named Pipes, and MSMQ. The main issue with WCF is its tedious and extensive configuration. It is not open source but can be consumed by any client that understands XML. It can be hosted within the application on IIS or using Windows service.

Web API Development in .NET 8 in 2 Hours | ASP.NET CORE | RESTFUL API
Web API Development in .NET 8 in 2 Hours | ASP.NET CORE | RESTFUL API

What is WCF?

WCF stands for Windows Communication Foundation. It is used to create a distributed and interoperable Applications. WCF is an effective platform for developing service-oriented applications. It allows developers to create secure, reliable, and high profile development solutions which can be integrated across platforms and interoperate with existing investments.

What is Web API?

ASP.NET Web API is a framework which allows you to build HTTP services for browsers and mobile devices. It is an ideal platform for developing RESTful applications on the ASP .NET Framework.

The ASP.NET Web API is an extensible framework for building HTTP based services that can be accessed in different applications on different platforms such a web, windows, mobile devices, etc.

Crear una WEB API REST en C# | .NET CORE 6 | (GET, POST, ETC) | HEADERS
Crear una WEB API REST en C# | .NET CORE 6 | (GET, POST, ETC) | HEADERS

WCF and ASP.NET Web API

WCF is Microsoft’s unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing investments. ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. This topic presents some guidance to help you decide which technology will best meet your needs.

Difference between WCF and Web API and WCF REST and Web Service: An Overview

The .Net framework has several technologies that allow you to create HTTP services such as Web Service, WCF, and now Web API. There are a lot of articles on the internet that may describe whom you should use, and gaining clarity on this topic is emphasized in ASP.NET Core training. Nowadays, you have a lot of choices for building HTTP services on the .NET framework.

In this Web API Tutorial, I would like to share my opinion with you on Web Service, WCF, and now Web API. For more information about Web API refer What is Web API and why to use it ?.

What is a Web API?
What is a Web API?

Conclusion

The conversion from WCF to ASP.NET Core Web API is possible and relatively easily manageable. The implementation of the WCF Services can be directly adopted for the new Web API controllers with minor adjustments to the return values and attributes. Using the OpenAPI specification allows you to generate a client for access to the Web API that supports the previous WCF ServiceContract interface. This way, only a few usings and the initialization of the client have to be adjusted in the consuming application.

WCF and ASP.NET Web API

WCF is Microsoft’s unified programming model for building service-oriented applications. It enables developers to build secure, reliable, transacted solutions that integrate across platforms and interoperate with existing investments. ASP.NET Web API is a framework that makes it easy to build HTTP services that reach a broad range of clients, including browsers and mobile devices. ASP.NET Web API is an ideal platform for building RESTful applications on the .NET Framework. This topic presents some guidance to help you decide which technology will best meet your needs.

Conclusion

We explained how to convert from a WCF service to an ASP.NET Core Web API service in this blog article. We examined the differences between the two technologies and offered code samples to assist you in getting started.

While migration might be difficult, it is critical to maintain your technology stack up to date in order to take advantage of new features, security upgrades, and performance enhancements.

You may assure a seamless and successful migration from WCF to ASP.NET Core Web API by following the procedures provided in this blog article.

This blog post in the series on alternatives for the Windows Communication Foundation (WCF) describes the particularities and challenges regarding a WCF migration in preparation of the subsequent porting of the application to .NET Core.

This post will first address ASP.NET Core Web API as a possible alternative, and describe, step by step, how a migration from WCF to ASP.NET Core Web API can be done. The procedure for the migration to gRPC, on the other hand, is described in the next blog post.

ASP.NET 7 Web API In Visual Studio 2022 and C# | Rest API In ASP.NET Core 7 And C# | Postman Swagger
ASP.NET 7 Web API In Visual Studio 2022 and C# | Rest API In ASP.NET Core 7 And C# | Postman Swagger

Migration procedure

Usually, there is a separate WCF project in the solution. As a direct conversion is not possible, this project can remain unchanged in the solution for the time being.

You should first create a new class library project for shared objects between the server and the client. Then copy the ServiceContract interfaces and the DataContract classes from the WCF project to this project, and remove the WCF-specific attributes such as “ServiceContract”, “OperationContract”, “DataContract”, “DataMember”, etc.

Client project

First of all, remove the WCF Service reference in the project that consumes the WCF Service. The WCF-specific attributes such as “CallbackBehavior” and the like can be removed as well.

Add a new reference to the previously created class library project for the shared objects.

Next, you can create an empty implementation of the ServiceContract interface, which is now located in the class library project, in the client project.

Now change the “old” initialization of the WCF Service to the, as-yet empty, implementation of the ServiceContract.

Lastly, you have to change the usings for the previously used DataContract classes from the WCF Service to the new class library project. It should now be possible to compile the client project again. In order to be able to start the project again, you have to remove the

from the *.config.

Web API project

Create a “standard” ASP.NET Core Web API project for the new server, and add a reference to the new class library project. This is necessary to enable the server to use the same replacement classes (previously DataContract) as the client.

Now create a controller for each previous WCF ServiceContract in the Web API. For starters, the implementation can be adopted from the “old” WCF Service. Subsequently, the return values have to be changed to ActionResult and ActionResult

, respectively. The [Http..] verb attributes and a route for each method have to be specified. Furthermore, the [ProducesResponseType] attribute should be specified for each method; it describes the expected return value and will later be used for the generation of the client.

[ServiceContract(CallbackContract = typeof(IDataCallback))] public interface IDataInputService { [OperationContract] int CreateUser(User user); [OperationContract] int Login(User user); [OperationContract] List

Example of a WCF Service Contract to be migrated

[Route(“api/TimeService”)] [ApiController] public class TimeServiceController : ControllerBase { [HttpPost(“CreateUser”)] [ProducesResponseType(typeof(int), 200)] public ActionResult

CreateUser(User user) { } [HttpPost(“Login”)] [ProducesResponseType(typeof(int), 200)] public ActionResult

Login(User user) { } [HttpGet(“Times”)] [ProducesResponseType(typeof(List


Example of the created Web API controller

Note: The Web API controller created this way will probably not correspond to a resource-oriented REST API. The API is more action-based and reflects the “old” Service—which is no problem for the transition for now.

Client generation

To avoid writing a lot of code for calling and using the Web API, you can generate it. The OpenAPI specification (formerly Swagger) can be used for this purpose.

There are several ways to generate the OpenAPI specification and, based thereon, the client code. One of these options is described below as an example.

In order for the OpenAPI specification to be generated automatically, you must first integrate the “NSwag.AspNetCor” NuGet package and configure it in the Web API project according to the instructions given in Getting started with NSwag. After that, you can already test the API interface in the browser by calling up the /swagger/ URL once the Web API project has been started.

The client code for access to the new Web API can be generated with NSwagStudio. In the settings of the generator, make sure that the namespace for the generation of the client is correct. Additional settings may be required for specific projects until the desired result is generated. The client created by the generator and the settings made in the generator (*.nswag file) should be saved in the project.

Use of the client

When the generator generates the desired result, you only need to make one more change to integrate the new client. The previously created, as-yet empty dummy implementation of the ServiceContract only has to inherit from the newly generated client, and the empty implementation has to be removed. It is important to ensure that the newly created client fulfills the ServiceContract interface.

The migration from WCF to Web API is now complete and should be tested.

Bidirectional communication

If bidirectional communication was used in the WCF Service, it must now be realized by means of SignalR.

For this purpose, create a hub class that inherits from Microsoft.AspNetCore.SignalR.Hub for each WCF CallbackContract in the Web API project. In the Startup.cs of the Web API project, add the line “services.AddSignalR();” in the ConfigureServices method. In the Configure method, a mapping is provided in the definition of UseEndpoints for each hub “endpoints.MapHub

(“/Earnings”);”.

public class Startup { public void ConfigureServices(IServiceCollection services) { services.AddSignalR(); } public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { app.UseEndpoints(endpoints => { endpoints.MapHub

(“/Earnings”); }); } } public class EarningsHub : Microsoft.AspNetCore.SignalR.Hub { }

Changes to the Web API startup class and definition of the SignalR Hub

By injecting IHubContext

, you can trigger the transmission of data to all or specific clients with just one line.

[Route(“api/TimeService”)] [ApiController] public class TimeServiceController : ControllerBase { private readonly IHubContext

earningsHubContext; public TimeServiceController(IHubContext

earningsHubContext) { this.earningsHubContext = earningsHubContext; } [HttpPost(“AddTime”)] [ProducesResponseType(200)] public ActionResult AddTime(Time time, int userId) { Task.Run(async () => await earningsHubContext.Clients.All.SendAsync(“EarningsCalculated”, result)).GetAwaiter().GetResult(); } }

Use of the SignalR hub in the API controller

Subsequently, add the “Microsoft.AspNetCore.SignalR.CIient” NuGet package to the consuming project. As you can see in the example below, the method previously called by the server does not have to be changed at all. In WCF, the method was triggered by means of the callback interface and its allocation upon initialization of the client with “new InstanceContext(this)”. With the SignalR implementation, a connection to the hub is established, and the triggering server event is bound to the existing method.

[CallbackBehavior(ConcurrencyMode = ConcurrencyMode.Single, UseSynchronizationContext = false)] public partial class TimeTracking : Page, IDataInputServiceCallback { private DataInputServiceClient client; public TimeTracking() { client = new DataInputServiceClient(new InstanceContext(this)); } public void EarningsCalculated(Dictionary

earnings) { // Client Methode welche vom Server aufgerufen wird } } [ServiceContract(CallbackContract = typeof(IDataCallback))] public interface IDataInputService { } public interface IDataCallback { [OperationContract(IsOneWay = true)] void EarningsCalculated(IDictionary

earnings); }

Client example using the WCF CallbackContract

public partial class TimeTracking : Page { private HubConnection connection; public TimeTracking() { connection = new HubConnectionBuilder().WithUrl(“http://localhost:52841/Earnings”).Build(); connection.On

>(“EarningsCalculated”, EarningsCalculated); connection.StartAsync(); } public void EarningsCalculated(Dictionary

earnings) { // Client Methode welche vom Server aufgerufen wird } }

Client example after conversion to SignalR

The use of SignalR described here as an example is very simple. For a productive deployment, you should ensure a robust implementation with automatic reconnect etc., see also: https://docs.microsoft.com/de-de/aspnet/core/signalr/dotnet-client?view=aspnetcore-3.1&tabs=visual-studio

Cross-cutting concerns such as authentication, authorization, logging and error handling of the Web API calls have not been considered in the migration. These issues should be checked and adjusted as well in each individual case.

Keywords searched by users: wcf to web api

Difference Between Web Api Vs Wcf - Youtube
Difference Between Web Api Vs Wcf – Youtube
Interview Question 2 Difference Between Web Api Vs Wcf - Youtube
Interview Question 2 Difference Between Web Api Vs Wcf – Youtube
Soap Và Rest, Asmx Và Wcf Web Service
Soap Và Rest, Asmx Và Wcf Web Service
Web Api Là Gì? Tài Liệu Web Api Tiếng Việt
Web Api Là Gì? Tài Liệu Web Api Tiếng Việt
Sự Khác Nhau Giữa Web Service, Wcf, Wcf Rest, Web Api
Sự Khác Nhau Giữa Web Service, Wcf, Wcf Rest, Web Api
C# : Wcf Service Or Web Api - Youtube
C# : Wcf Service Or Web Api – Youtube
Tweaking Wcf To Build Highly Scalable Async Rest Api - Codeproject
Tweaking Wcf To Build Highly Scalable Async Rest Api – Codeproject
Difference Between Wcf And Web Api
Difference Between Wcf And Web Api
Difference Between Wcf And Web Api And Wcf Rest And Web Service
Difference Between Wcf And Web Api And Wcf Rest And Web Service
Consume Wcf Web Services In C# .Net Core – Best Practices | Thecodebuzz
Consume Wcf Web Services In C# .Net Core – Best Practices | Thecodebuzz
Wcf End-To-End | Pluralsight
Wcf End-To-End | Pluralsight
Sự Khác Nhau Giữa Web Service, Wcf, Wcf Rest, Web Api
Sự Khác Nhau Giữa Web Service, Wcf, Wcf Rest, Web Api
Web Api Là Gì Và Ưu Điểm Của Nó So Với Wcf Rest Service
Web Api Là Gì Và Ưu Điểm Của Nó So Với Wcf Rest Service

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 *