Web service vs Web API (What's the real difference) - c#

Can someone explain me the difference between Web services & web API? I have gone through so many blogs but all of them seems to be using the same bookish knowledge. What's the actual difference between them in real terms?

As #Dai explained the zest and I completely agree with him. In addition, I would like to provide you some real-life difference besides.
Web Service:
As Web Service basically, used WSDL which used to communicate with SOAP or XML base service. However, the main challenge in Web Service was to handle cross-platform request. We used to add service reference as following way: While developped Web Services.
Web API:
Considering these drawbacks, Microsoft, latter on developed the Web API more specifically, Asp.net Web API which provide the robust functionality for cross platform development using REST pattern mostly used Json data. It doesn’t mean that web service cannot do that, but not robust as Web API now a days. Unlike, web service we don’t need to go through any integration hassle as above which we can directly develop using asp.net core project and can open the route to call from anywhere.For instance below example:
[ApiController]
[Route("api/VehicleFilter")]
public class VehicleFilterController : ControllerBase
{
private readonly ApplicationDbContext _context;
private readonly IWebHostEnvironment _environment;
public VehicleFilterController(IWebHostEnvironment environment, ApplicationDbContext context)
{
_environment = environment;
_context = context;
}
[HttpGet]
public async Task<IActionResult> GetAllFilter()
{
string VehicleName = "Hatchback";
var sqlCommand = $"EXEC GetVehicleByTile {VehicleName}";
var vehicleFilterValues = await _context.VehicleFilter.FromSqlRaw(sqlCommand).ToListAsync();
return Ok(vehicleFilterValues);
}
}
To summarize, Web API provides more flexibility and robustness and of course its lightweight while writing any new method. Where web service leads to some demerits to the developer.

Related

Prevent collisions when working with RabbitMq from two or more instances of the same app

Good time, Stack Overflow community.
I have some questions about software architecture i'm working on and i will appreciate for help with them.
The components of the app are following:
Model project (net core class library). Here i define model classes & database context.
Business project (net core class library). It has reference on the Model assembly and implements business logic. Also here, placed a HostedService with code for working with microservices through EasyNetQ using Send/Receive & Request/Response patterns.
Web API project (net core web api app). It uses Business assembly and provides web api features. This app hosted on iis 10.
Web frontend project (net core razor web app). It also uses Business assembly and provides web UI features. This app hosted on iis 10.
Some microservice apps, that may communicate with Business assembly through EasyNetQ by receiving and sending messages. Every microservice runs in the one instance.
Web api app and web frontend app both working simultaneously. So we have two instances of business logic assembly working at the same time and both of them works with the same rabbitmq queues.
So, i'm afraid that one instance of Business assembly may send message to microservice (IBus.Send), but second instance of Business assembly may receive the message from microservice (IBus.Receive). In this case, as i understand, may be collision because the first instance of Business waits answer and does not receive it, at the same time second instance of Business receives not waitable answer.
A bit of code.
Web api app startup:
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddBusiness(Configuration);
...
}
Web frontend app startup:
public void ConfigureServices(IServiceCollection services)
{
services.AddBusiness(Configuration);
...
}
Business logic assembly startup:
public static IServiceCollection AddBusiness(this IServiceCollection services, IConfiguration configuration)
{
...
services.AddSingleton(sp =>
{
var rabbitMqSettings = sp.GetRequiredService<IOptions<RabbitMqSettings>>();
return RabbitHutch.CreateBus(rabbitMqSettings.Value.Connection);
});
services.AddHostedService<RabbitMessagesReceiverService>();
return services;
}
Business logic assembly EasyNetQ code examples:
public class RabbitMessagesReceiverService : BackgroundService
{
readonly IBus _bus;
public RabbitMessagesReceiverService(IBus bus)
{
_bus = bus;
}
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
// receives messages from microservice
_bus.Receive<OutgoingResult>(RabbitHelper.OUTGOING_RESPONSE, async response =>
{
...
}
}
}
or
// sends message to microservice
await _bus.SendAsync<OutgoingRequest>(RabbitHelper.OUTGOING_REQUEST, new OutgoingRequest
{
...
});

how does host differentiate MVC request and Web API request

I'm new to asp.net mvc and web api. I'm reading a book which says:
ASP.NET MVC uses: System.Web.HttpRequest
and Web API Equivalent is System.Net.Http.HttpRequestMessage
and below is a picture that describes the request and result flow of web api
So my question is, how does hosting environment(which will typically be IIS) know that it should create a HttpRequestMessage object to represent the request from the client? I mean if the application is a MVC application, IIS should create a HttpRequest object instead of HttpRequestMessage, so how does IIS know which one to create?
As you can see from the picture you posted, the HttpRequestMessage exists only inside the "hosting" environment, web browser client does not know anything about that.
In the "hosting" world, IIS app pool is running the code you have built and deployed which knows very well wich framewok you are using as your code also contains the using assemblies you listed, System.Web... or System.Net...
Consider that even if you have shown separation between hosting, Controller and Action, all of that is running in same App Pool in IIS which, again, runs your code so knows what it is about as your IL assemblies were built from your specific source code.
I am not sure if I understand your question but this might be what you're looking for:
I mean if the application is a MVC application, IIS should create a
HttpRequest object instead of HttpRequestMessage, so how does IIS know
which one to create?
You must remember how you differentiate between a normal MVC Controller and a Web API Controller...
WebAPI Controllers enforces this annotation [ApiController] and must inherits from ControllerBase:
[ApiController]
public class PeopleController : ControllerBase {
//Your API methods here
}
A normal MVC Controller only inherits from Controller base class:
public class PeopleController : Controller {
//Your Action methods here...
}
Those already create configuration for your APP which becomes easier for you Hosting environment to know what is going and what to return when.
I hope you find this helpful.

owin self hosting using soket with web api

I want to open webSocket by web api post request.
I tryed to use HttpContext.Current.AcceptWebSocketRequest but it didn't work (as you can see in the following example) because HttpContext.Current is null in self host.
public class ChatController : ApiController
{
public HttpResponseMessage Get(string username)
{
HttpContext.Current.AcceptWebSocketRequest(new ChatWebSocketHandler(username));
return Request.CreateResponse(HttpStatusCode.SwitchingProtocols);
}
}
Is there a way to get the current http context without IIS?
Or what is the best way to open websocket?

Implementing PostSharp with Asmx Web Service

I'm currently trying to integrate postsharp with my asmx web service for the purpose of logging exceptions.
Here's my code for the Aspect perspective:
[Serializable]
public class LogPerformance : OnMethodBoundaryAspect
{
public override void OnEntry(MethodExecutionArgs args)
{
string test = "test";
base.OnEntry(args);
}
public override void OnExit(MethodExecutionArgs args)
{
string test = "test";
base.OnExit(args);
}
public override void OnException(MethodExecutionArgs args)
{
string test = "test";
base.OnException(args);
}
}
while in my Service.cs class, i've the following web method:
[WebMethod(EnableSession = true)]
[SoapHeader("authentication")]
[LogPerformance]
public DataTable loginUser(string userName, string password)
{
doStuff();
}
Coming straight to the point:
Does postsharp support implementation with web methods? As in my case,
postSharp methods does not get called whenever the web method receives
a hit. (Yes i've added postsharp reference using Nuget and/or/plus manually added its dll as well) This does
suggest a step towards the mentioned subject but i could not make anything
out of it.
It is important to note that the same LogPerformance Class runs smoothly when integrated with:
Web API
ASP.Net Web Application (MVC)
Console Application
The problem is when i use it with .asmx web service. A little nudge towards the right direction would be appreciated.
The *.asmx web-services are supported by PostSharp. However, you need to pay attention whether your ASP.NET project is a Web Site or a Web Application (ASP.NET Web Site or ASP.NET Web Application?). Only Web Application projects are supported by PostSharp. For more information on compatibility you can also check Requirements and Compatibility.
You can convert your Web Site project to Web Application project by following the guidelines from the blog post Converting a Web Site Project to a Web Application Project. After the conversion you need to install PostSharp NuGet package into your project.

How to implement SOAP service on WebAPI

We have a server which has several types of api (custom XML API based on httplistener, SOAP API based on WCF and REST API based on WEB API). We want to move all API's to WEB API (there are many reasons) and it should be backward compatible.
One of the reason to support url structure: services/service1. services/service2. And in this case it should be on one port. It is intranet application which is distributed to multiple customers and it should be easy to deploy, install. So, we can not have a long configuration on customer side (proxing and otherts).
Are there easy way for implementation SOAP service on web api? At first look should be easy way to parse httprequest to typed soap envelope (based on existed contract) and serialize a answer. Of course, there many actions and data types in contract.
PS: I do not want to look into servicestack:)
Update:
The problem I described above can be fixed by proxing http request to soap service (It can work only with basichttpbinding without security. If WCF service require NTLM authentication it won't work):
[HttpPost]
public async Task<IHttpActionResult> SoapAction()
{
var httpClient = new HttpClient();
var httpRequestMessage = new HttpRequestMessage(HttpMethod.Post, "http://localhost:8111/soap")
{
Content = this.Request.Content
};
foreach (var header in this.Request.Headers)
{
httpRequestMessage.Headers.Add(header.Key, header.Value);
}
var responseMessage= await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false);
return ResponseMessage(responseMessage);
}
But I still want to know are there any SOAP parser in C# because my server supports NTLM authentication.
I wouldn't recommend to mix the technologies. Have one project for SOAP Apis and another one for the WebApi, sharing the same logic.
You have then one url for soap, the other one to webapi.
Edit:
I wouldn't do the SOAP Parser at all. That was the power of WCF and would keep on using it.
Since proxing is not an option (Which could be done in web.config and easily deployed), I would create a WebAPI endpoint which would redirect to SOAP API.
[HttpGet]
public IHttpActionResult Service1()
{
return Redirect("http://service.com/soap/services/service1");
}
Later, when migrating the logic, use the service itself.
[HttpGet]
public IHttpActionResult Service1()
{
var result = new ServiceLogin1().Execute();
if(result == null)
{
return StatusCode(HttpStatusCode.NoContent);
}
else
{
return Ok();
}
}
I think this is already answered here ASP.NET WebAPI + Soap
If what you are asking for is how to create REST wrappers that call into the SOAP implementations then library's like ServiceStack do this for you but if you want to do it yourself with WebApi it's pretty easy. Just make a separate project that has your SOAP service references in it wrapped in some sort of abstraction and then reference that in your WebApi project and call into it from your REST endpoints.
If what you are asking is how to host the SOAP interfaces in WebApi I think you are just making more work for yourself. Use the WCF scaffolding that MS has provided. WebApi for REST services, WCF for SOAP.

Categories