Swagger with ASP.Net Core 2.0 Web API


Swagger with ASP.Net Core 2.0 Web API

Swagger is a open source framework, which helps to create API documentation.

Using swagger, developer does not need to mention to developer who want to consume API, its straight forward to visualization.

Here, we will see that how to use swagger with ASP.Net core 2.0 web API.
First install "Swashbuckle.AspNetCore" using nuget package manager.

Add swagger service to application services, Open startup.cs and do following changes.

public void ConfigureServices(IServiceCollection services)
{
 services.AddMvc();

 services.Configure<IISOptions>(options =>
 {
  options.ForwardClientCertificate = false;
 });

 services.AddSwaggerGen(c =>
 {
  c.SwaggerDoc("v1", new Info
  {
   Version = "v1",
   Title = "Demo Service",
   Description = "Demo Service Description",
   TermsOfService = "None",
   Contact = new Contact() { Name = "Rohit Rathod", Email = "anrorathod@gmail.com", Url = "www.mywebsite.com" }
  });
 });
}

Here, SwaggerDoc Info properties are optional (Version, Title, Description, TermsOfService and Contact).


Now, write below code to enable swagger UI,

public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
 if (env.IsDevelopment())
 {
  app.UseDeveloperExceptionPage();
 }

 app.UseMvc();

 string appPath = "/DemoService.WebAPI/";
 app.UseSwagger();
 app.UseSwaggerUI(c =>
 {
  c.SwaggerEndpoint(appPath + "swagger/v1/swagger.json", "Demo Service");
 });
} 

Now, build web API application, open web browser and run application and you will see API documentation.

http://localhost/DemoService.WebAPI/swagger/

I hope that this will helpful in your web API project.

Enjoy !!!



:)

Consume web API in MVC or Windows Application or Console Application

Consume web API in MVC or Windows Application or Console Application

Sometime, we need to consume web API mostly in MVC or Windows Service or Windows Application or Console Application.  

Below code posts dynamic object in API call,


var url = "http://localhost/DemoWebAPIProject/api/ControllerName/Method";

Uri requestUri = new Uri(url);  
dynamic dynamicObject = new ExpandoObject();
dynamicObject.UserName = "anorathod".ToString();
dynamicObject.Password = "password";

string json = "";
json = Newtonsoft.Json.JsonConvert.SerializeObject(dynamicObject);

var httpClient = new HttpClient();
HttpResponseMessage response = await httpClient.PostAsync(requestUri, new StringContent(json, System.Text.Encoding.UTF8, "application/json"));

string responJsonText = await response.Content.ReadAsStringAsync()

I hope that this will helpful in your project.

Enjoy !!!

:)

Useful links for .Net Developer


Useful links for .Net Developer



I found some links while doing development and R & D, I feel that I have to keep these links and articles, so I have started to store it here. I will keep updated this page regularly... 



1. Consume web api in MVC or windows application or Console Application

https://www.c-sharpcorner.com/UploadFile/2b876a/consume-web-service-using-httpclient-to-post-and-get-json-da/


2. Building An ASP.NET Core Application With Web API And Code First Development

3. Unity Dependency Injection 

3.1 ASP.NET MVC 4 Dependency Injection

3.2 Dependency Injection in ASP.NET Web API 2

3.3 C# – Using Unity for Dependency Injection in an ASP.NET MVC 4 Web API
https://myadventuresincoding.wordpress.com/2013/03/27/c-using-unity-for-dependency-injection-in-an-asp-net-mvc-4-web-api/

4. Swagger
4.1 For .Net Framework
Swagger integration in ASP.NET Web API project
https://code.msdn.microsoft.com/Swagger-integration-in-da408b29

4.2 For .Net Core
Add Swagger to ASP.NET Core 2.0 Web API
http://www.talkingdotnet.com/add-swagger-to-asp-net-core-2-0-web-api/

5. SQL Cache dependency
5.1 How to implement SQL Caching in ASP.NET (Poll based SQL Cache dependency)?
https://www.youtube.com/watch?v=RxbhQy8EIzM

5.2 How to use Push SQL Cache dependency in ASP.Net?
https://www.youtube.com/watch?v=nJFTfkr-U-Y

6. Create and publish a (nuget) package using Visual Studio (.NET Standard)
https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package-using-visual-studio

7. CQRS - Command-Query Responsibility Segregation

Introduction to CQRS
https://www.codeproject.com/Articles/555855/Introduction-to-CQRS

A Beginner's Guide To Implementing CQRS ES
https://github.com/Chinchilla-Software-Com/CQRS/wiki/A-Beginner's-Guide-To-Implementing-CQRS-ES

Part-1 Implementing CQRS/ES in ASP.NET
https://www.exceptionnotfound.net/implementing-cqrs-in-net-part-1-architecting-the-application/

Part-2 Implementing CQRS in .NET Part 2: Handling Commands and Events
https://www.exceptionnotfound.net/implementing-cqrs-in-net-part-2-handling-commands-and-events/

Part-3 Implementing CQRS in .NET Part 3: The Commands Interface
https://www.exceptionnotfound.net/implementing-cqrs-in-net-part-3-the-commands-interface/

Part-4 Implementing CQRS in .NET Part 4: More Events and Summary
https://www.exceptionnotfound.net/implementing-cqrs-in-net-part-4-more-events-and-summary/

8. Dependency Injection for Multiple Concrete Implementations of an Interface
http://www.intstrings.com/ramivemula/articles/dependency-injection-for-multiple-concrete-implementations-of-an-interface/

9. How to register and use Multiple Classes Implementing Same Interface in AutoFac?
https://www.codeproject.com/Tips/870246/How-to-register-and-use-Multiple-Classes-Implement



10. Introduction To ASP.NET WebAPI And Return Result In Different Formats (as XML or JSON)
https://www.c-sharpcorner.com/UploadFile/manas1/introduction-to-Asp-Net-webapi-and-returns-result-in-differe/


11. Recursive Select in C# and LINQ
https://bitlush.com/blog/recursive-select-in-c-sharp-and-linq

Recursive Hierarchical Joins in C# and LINQ
https://bitlush.com/blog/recursive-hierarchical-joins-in-c-sharp-and-linq

12. Azure Scheduler job collection
http://fabriccontroller.net/a-complete-overview-to-get-started-with-the-windows-azure-scheduler/

 https://github.com/Azure-Samples/scheduler-dotnet-getting-started

13. ASP.NET WEBFORM: DATATABLES JQUERY PLUGIN SERVER SIDE INTEGRATION
14. Online dotnet editor and testing - https://dotnetfiddle.net




If you have good links for .net development then please add in comment or contact me.

Cheers :)


ASP.Net Core API - HTTP Error 405.0 - Method Not Allowed

ASP.Net Core API - HTTP Error 405.0 - Method Not Allowed

I have created web api for delete in ASP.Net core C#, while I execute delete method in Postman (with method = DELETE ), I got below error...

HTTP Error 405.0 - Method Not Allowed

<ul>
 <li>The request sent to the Web server used an HTTP verb that is not allowed by the module configured to handle the request.</li>
 <li>A request was sent to the server that contained an invalid HTTP verb.</li>
 <li>The request is for static content and contains an HTTP verb other than GET or HEAD.</li>
 <li>A request was sent to a virtual directory using the HTTP verb POST and the default document is a static file that does not support HTTP verbs other than GET or HEAD.</li>
</ul>

I found below solution after searching on internet and it is working fine for me.

I added below configuration in web.config file.

  <system.webServer>
     <validation validateIntegratedModeConfiguration="false"/>
    <modules runAllManagedModulesForAllRequests="true">
        <remove name="WebDAVModule"/>
   </modules>    
  </system.webServer

Hope, this will help to resolve your issue...

Enjoy !!!

:)

Azure Service Bus - Send & Receive Message - Topic in .Net Core

Azure Service Bus - Send & Receive Message - Topic in .Net Core




I have seen many examples to send and receive message of Azure Service Bus Topic in normal .Net framework, but I couldn't find correct code for .Net Core for the same to send and receive Azure Service Bus Topic.

Finally, I got solution and here is code for .Net Core C#.

Send Message

1. Create web api project with .Net core
2. Add Service Bus NuGet package, search for "Microsoft.Azure.ServiceBus"
3. Add NuGet package for "Newtonsoft.Json"
4. Create Test API controller
5. Write below code

using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc; 
using Microsoft.Azure.ServiceBus;
using Newtonsoft.Json; 
using System.Collections.Generic; 
using System.Text; 

namespace Demo.WebAPI.Controllers
{
    [Produces("application/json")]
    [Route("api/Test")]
    public class TestController : Controller
    {
        [HttpPost]
        public async Task<IActionResult> Post(dynamic model)
        {
            try
            {
                await Task.Run(() =>
                {
                    MessageFactory.SendMessagesAsync("TestTopic",
                           "testLable", 60, model);
                });
            }
            catch (Exception ex)
            {

                return Ok(ex.Message);
            }

            return Ok("Request submitted. ");
        }
        public static async Task SendMessagesAsync(string topicName, string lable, int minsTimeToLive, dynamic model, Dictionary<string, string> properties = null)
        {
            try
            {
                ITopicClient topicClient = new TopicClient(Config.ConnectionString, topicName);

                Message message = new Message(Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(model)))
                {
                    ContentType = "application/json",
                    Label = "test",
                    TimeToLive = TimeSpan.FromMinutes(minsTimeToLive)
                };

                await topicClient.SendAsync(message);
            }
            catch (Exception exception)
            {

            }
        }
    } 
}


Test Web API 

1. Open Postman or restclient to test web api
2. URL :http://localhost/Demo.WebAPI/api/Test
2. Content-Type = application/json
3. Type: POST
4. Body as below,

 {
  "OrderDate":"02/22/2018",
  "CustomerId": 28,
  "Amount":35.23,
  "PaymentType":"Online",
  "Products":[
   {
    "ProductId":1,
    "Quantity":2,
    "Amount":10
   },
   {
    "ProductId":3,
    "Quantity":1,
    "Amount":15
   }
   ],
   "ShippingAddress":
   {
    "ShippingBy":"BlueDart",
    "CustomerName":"Test Customer",
    "Address":"Address 1",
  "Email":"test@test.com",
  "Phone":"1234567890"
   }
}

After posting request, you should get Status = 200 OK


Receive Message

1. Create .Net Core console application
2. Add reference using nuget for "Microsoft.Azure.ServiceBus" and "Newtonsoft.Json"
3. Write below code to receive azure service bus topic message

using System;
using System.IO;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.ServiceBus;
using Newtonsoft.Json; 

namespace Demo.Service
{
    class Program
    {
        const string ServiceBusConnectionString = "Endpoint=sb://[NameSpace].servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=[SharedAccessKey]=";
        const string TopicName = "TestTopic";
        const string SubscriptionName = "TestSubscriber";
        static ISubscriptionClient subscriptionClient;

        static void Main(string[] args)
        {
            Console.WriteLine("Service started...");

            while (true)
            {
                MainAsync().GetAwaiter().GetResult();
            }

        }

        static async Task MainAsync()
        {
            subscriptionClient = new SubscriptionClient(ServiceBusConnectionString, TopicName, SubscriptionName);

            RegisterOnMessageHandlerAndReceiveMessages();

            await subscriptionClient.CloseAsync();
        }

        static void RegisterOnMessageHandlerAndReceiveMessages()
        {
            // Configure the message handler options in terms of exception handling, number of concurrent messages to deliver, etc.
            var messageHandlerOptions = new MessageHandlerOptions(ExceptionHandler)
            {
                // Maximum number of concurrent calls to the callback ProcessMessagesAsync(), set to 1 for simplicity.
                // Set it according to how many messages the application wants to process in parallel.
                MaxConcurrentCalls = 1,

                // Indicates whether MessagePump should automatically complete the messages after returning from User Callback.
                // False below indicates the Complete will be handled by the User Callback as in `ProcessMessagesAsync` below.
                AutoComplete = false
            };

            // Register the function that processes messages.
            subscriptionClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
        }

        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            var a = new MemoryStream(message.Body);

            var body = Encoding.UTF8.GetString(message.Body);

            Order order = JsonConvert.DeserializeObject<Order>(body);

            // Process the message.
            Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");
            // Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Id = { order.OrderId}");
            // Complete the message so that it is not received again.
            // This can be done only if the subscriptionClient is created in ReceiveMode.PeekLock mode (which is the default).
            await subscriptionClient.CompleteAsync(message.SystemProperties.LockToken);

            // Note: Use the cancellationToken passed as necessary to determine if the subscriptionClient has already been closed.
            // If subscriptionClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc.
            // to avoid unnecessary exceptions.
        }

        static Task ExceptionHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
        {
            Console.WriteLine($"Message handler encountered an exception {exceptionReceivedEventArgs.Exception}.");
            var context = exceptionReceivedEventArgs.ExceptionReceivedContext;
            Console.WriteLine("Exception context for troubleshooting:");
            Console.WriteLine($"- Endpoint: {context.Endpoint}");
            Console.WriteLine($"- Entity Path: {context.EntityPath}");
            Console.WriteLine($"- Executing Action: {context.Action}");
            return Task.CompletedTask;
        }
    }
}



Add classes to do business process....

public class Order
{
 public Guid OrderId { get; set; }
 public int CustomerId { get; set; }
 public string InvoiceNo { get; set; }
 public DateTime OrderDate { get; set; }
 public bool Payment { get; set; }
 public string OrderStatus { get; set; }
 public string PaymentType { get; set; }
 public decimal Amount { get; set; }

 public List<OrderItems> Products { get; set; }
 public ShippingAddress ShippingAddress { get; set; }
}
public class OrderItems
{
 public int ProductId { get; set; }
 public int Quantity { get; set; }
 public decimal Amount { get; set; }
}
public class ShippingAddress
{
 public Int64 ShippingId { get; set; }
 public Guid OrderId { get; set; }
 public DateTime ShippingDate { get; set; }
 public string ShippingBy { get; set; }
 public string CustomerName { get; set; }
 public string Address { get; set; }
 public string Email { get; set; }
 public string Phone { get; set; }
 public string ShippingStatus { get; set; }

}


Run console application and you will receive azure service bus message.



Enjoy !!!

:)