Host .Net Core Web API on IIS - ISSUE

Host .Net Core Web API on IIS - ISSUE

After uploaded .Net Core web API on IIS server, I faced below issue , but I found solution after some trial and error.


Issue

<div class = "content-container">
 <h3> HTTP Error 502.5 - Process Failure </h3>
</div>
<div class = "content-container">
 <fieldset>
  <h4> Common causes of this issue: </h4>
  <ul>
   <li> The application process failed to start </li>
   <li> The application process started but then stopped </li>
   <li> The application process started but failed to listen on the configured port </li>
  </ul>
 </fieldset>
</div>

Solution

Open web.config file and make some changes as below

Existing Configuration

<aspNetCore processPath="dotnet" arguments=".\CoreApp.dll -argFile IISExeLauncherArgs.txt" forwardWindowsAuthToken="false" startupTimeLimit="3600" requestTimeout="23:00:00" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />

Working Configuration:

<aspNetCore processPath="dotnet" arguments=".\CoreApp.dll -argFile IISExeLauncherArgs.txt" forwardWindowsAuthToken="false" startupTimeLimit="3600" requestTimeout="23:00:00" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />

 1. I had removed ".\" before dll name, as I hosted my application on root folder on server.

2. Removed -argFile IISExeLauncherArgs.txt

I hope that you also resolve your issue by using this solution.


Enjoy !!!

:)

Code First Migration in ASP.Net Core

Code First Migration in ASP.Net Core

Generally we create database first and then we create data model classes in project, and while we publish application we need to take care about database creation and table.

Code first, its approach that we first create data model classes and code itself create database and while publishing application, we don't need to take care about database and its tables, code automatically manage.

While executing code first migration command in .Net Core C#, we are facing some issues sometimes, here I faced some issues and found some solutions as below.

Issue 1

Getting error, while executing command 

Add-Migration -Context "DatabaseContext" 

 Unable to create an object of type 'DatabaseContext'. Add an implementation of 'IDesignTimeDbContextFactory<DatabaseContext>' to the project, or see https://go.microsoft.com/fwlink/?linkid=851728 for additional patterns supported at design time.

Solution 

public class DesignTimeDbContextFactory : IDesignTimeDbContextFactory<DatabaseContext>
{
 public DatabaseContext CreateDbContext(string[] args)
 {
  IConfigurationRoot configuration = new ConfigurationBuilder()
   .SetBasePath(Directory.GetCurrentDirectory())
   .AddJsonFile("appsettings.json")
   .Build();
  var builder = new DbContextOptionsBuilder<DatabaseContext>();
  var connectionString = configuration.GetConnectionString("dbConStr");
  builder.UseSqlServer(connectionString);
  return new DatabaseContext(builder.Options);
 }
}

Issue 2

Getting error, while executing below command

Add-Migration -Name "Migration Name" -Context "DatabaseContext"

GenericArguments[0], 'SampleWebAPI.Migrations.DatabaseContext', on 'Microsoft.EntityFrameworkCore.Design.IDesignTimeDbContextFactory`1[TContext]' violates the constraint of type 'TContext'.

Solution 

1. First remove migration folder (if any) from project which was created by above command

Issue 3

Getting error, while executing command 

Update-Database 

More than one DbContext was found. Specify which one to use. Use the '-Context' parameter for PowerShell commands and the '--context' parameter for dotnet commands.

Solution 

Update-Database -Context "DatabaseContext"

Finally

Use below migration commands for .Net Core


1. Add-Migration -Name "Migration Name" -Context "DatabaseContext"

2. Update-Database -Context "DatabaseContext"



Enjoy !!!

:)

Code First Steps in ASP.Net C#

Code First Steps in ASP.Net C#

Generally we create database first and then we create data model classes in project, and while we publish application we need to take care about database creation and table.

Code first, its approach that we first create data model classes and code itself create database and while publishing application, we don't need to take care about database and its tables, code automatically manage.

Lets see, how to work with code first in .Net C#

Steps

1.First provide connection string in web.config file.
<connectionStrings>
    <add name="conDemoDB" connectionString="data source=ServerName; initial catalog=dbName; user id=username; password=password;" providerName="System.Data.EntityClient"/>
  </connectionStrings>

2. Create data model classes as per your requirement

3. Install Entity Framework using nu-get package installer or command 

4. Create DataContext Class

using System.Data.Entity;
using System.Data.Entity.Infrastructure;
 
namespace DemoApp.Reporsitory
{
    public class dataContext : DbContext
    {
        public dataContext()
            : base("name=conDemoDB")
        {
        }
 
        public virtual DbSet<Menu> Menus { get; set; }
        public virtual DbSet<MenuItem> MenuItems { get; set; }
    }
}


5. Open Package Manager Console from Tools -> NuGet Package Manager

1. Enable-Migrations  

2. Add-Migration "Comments"

3. Update-Database -Verbose 

Once command executes successfully, you can open database and check that tables are created.

for more detail, https://docs.microsoft.com/en-us/ef/ef6/modeling/code-first/migrations/automatic

Enjoy !!!

:)

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 !!!

:)