Add Swagger UI in Asp.Net CORE API 3.1

Tech Requirements:

Visual Studio 2019 Community Edition
Asp.Net Core 3.1 SDK
Nuget Packages:

Steps to implementation:

Create a project for .Net Core API
Add below Nuget Packages using Nuget Package Manager Console

Code Snippet:

 Configure Swagger in Project

// 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())
//Enable middleware to serve generated Swagger as a JSON endpoint.
// Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.),
// specifying the Swagger JSON endpoint.
app.UseSwaggerUI(c =>
c.SwaggerEndpoint(“/swagger/v1/swagger.json”, “My API V1”);




app.UseEndpoints(endpoints =>

Configure Swagger Dependency Service

// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
// Register the Swagger generator, defining 1 or more Swagger documents
services.AddSwaggerGen(c =>
c.SwaggerDoc(“v1”, new OpenApiInfo
Title = “Employee API”,
Version = “v1”,
Description = “An API to perform Employee operations”,
TermsOfService = new Uri(“”),
Contact = new OpenApiContact
Name = “Tes User”,
Email = “”,
Url = new Uri(“”),
License = new OpenApiLicense
Name = “Employee API LICX”,
Url = new Uri(“”),
// Set the comments path for the Swagger JSON and UI.
var xmlFile = $”{Assembly.GetExecutingAssembly().GetName().Name}.xml”;
var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile);

Swagger Output:

Securely post multiple models in one request in MVC application

Securely post multiple models in one request in MVC application

Real-Time Sample: CRM in MVC

Suppose we have a requirement of adding a customer with Their Branch, Follow up details

Step 1: Firstly make jquery object models to be post data in single request

Customer Model
var customerViewModel = {
CustomerId: hdnCustomerId.val(),
CustomerCode: txtCustomerCode.val().trim(),
CustomerName: txtCustomerName.val().trim(),
ContactPersonName: txtContactPersonName.val().trim(),
Designation: txtDesignation.val().trim(),
Email: txtEmail.val().trim(),
MobileNo: txtMobileNo.val().trim(),
ContactNo: txtContactNo.val(),
Fax: txtFax.val().trim(),
PrimaryAddress: txtPrimaryAddress.val().trim(),
City: txtCity.val().trim(),
StateId: ddlState.val(),
CountryId: ddlCountry.val(),
PinCode: txtPinCode.val().trim(),
CSTNo: txtCSTNo.val().trim(),
TINNo: txtTINNo.val().trim(),
PANNo: txtPANNo.val().trim(),
GSTNo: txtGSTNo.val().trim(),
ExciseNo: txtExciseNo.val().trim(),
EmployeeId: hdnEmployeeId.val(),
CustomerTypeId: ddlCustomerType.val(),
CreditLimit: txtCreditLimit.val().trim(),
CreditDays: txtCreditDays.val().trim(),
Customer_Status: chkStatus,
GST_Exempt: GSTExempt


Customer Branch Model
var customerBranch = {
CustomerBranchId: customerBranchId,
BranchName: branchName,
ContactPersonName: bContactPersonName,
Designation: bDesignation,
Email: bEmail,
MobileNo: bMobileNo,
ContactNo: bContactNo,
Fax: bFax,
PrimaryAddress: bAddress,
City: bCity,
StateId: bStateId,
StateName: bStateName,
CountryId: bCountryId,
PinCode: bPinCode,


Cstomer Follow Up Model
var customerFollowup = {
CustomerFollowUpId: CustomerFollowUpId,
FollowUpActivityTypeId: FollowUpActivityTypeId,
FollowUpActivityTypeName: FollowUpActivityTypeName,
FollowUpDueDateTime: FollowUpDueDateTime,
FollowUpReminderDateTime: FollowUpReminderDateTime,
FollowUpRemarks: FollowUpRemarks,
Priority: Priority,
PriorityName: PriorityName,
FollowUpStatusId: FollowUpStatusId,
FollowUpStatusName: FollowUpStatusName,
FollowUpStatusReason: FollowUpStatusReason,
FollowUpByUserId: FollowUpByUserId,
FollowUpByUserName: followUpByUserName


Step 2: Make ajax call to be post data

var requestData = {
customerViewModel: customerViewModel,
customerBranchs: customerBranchList,
customerProducts: customerProductList,
customerFollowUps: customerFollowUpList };
url: “../Customer/AddEditCustomer”,
cache: false,
type: “POST”,
dataType: “json”,
data: JSON.stringify(requestData),
contentType: ‘application/json’,
success: function (data) {
if (data.status == “SUCCESS”) {
ShowModel(“Alert”, data.message);
function () {
window.location.href = “../Customer/AddEditCustomer”;
}, 2000);

else {
ShowModel(“Error”, data.message)
error: function (err) {
ShowModel(“Error”, err)

Step 3: Pass data to Action Method to be perform data

public ActionResult AddEditCustomer(CustomerViewModel customerViewModel, List<CustomerBranchViewModel> customerBranchs, List<CustomerProductViewModel> customerProducts,List<CustomerFollowUpViewModel> customerFollowUps)
{ }

If any issues contact with us on :

Implement google recaptcha in MVC and Asp.NET application

Step 1: Generate Site Key and Secret Key for recaptcha

Go through the link:

Then generate you Site Key and Secret Key like below image


Google recaptcha

Step 2: Make div like this on your page where you want to implement captcha

<div id=”CaptchaVal” class=”g-recaptcha” data-sitekey=”Your Site Key“></div>

Step 3: Validate you captcha code by this server side code

public static bool ValidateCaptcha(string response)
string secretkey = System.Configuration.ConfigurationManager.AppSettings[“secretkey”];
string secret = secretkey;
var client = new WebClient();
var reply = client.DownloadString(string.Format(“{0}&response={1}”, secret, response));
var captchaResponse = JsonConvert.DeserializeObject<CaptchaResponse>(reply);
return Convert.ToBoolean(captchaResponse.Success);

if any issue you can contact with us on

Post multiple entities in single request MVC

Post Multiple Entities in single request in Linq:

public ResponseOut AddEditCustomer(CustomerViewModel customerViewModel, List<CustomerBranchViewModel> customerBranchs, List<CustomerProductViewModel> customerProducts,List<CustomerFollowUpViewModel> customerFollowUps)
ResponseOut responseOutBranch = new ResponseOut();
ResponseOut responseOutProduct = new ResponseOut();
ResponseOut responseOut = new ResponseOut();
ResponseOut responseOutSL = new ResponseOut();
ResponseOut responseOutFollowUp = new ResponseOut();
using (TransactionScope transactionscope = new TransactionScope())
Customer customer = new Customer
CustomerId = customerViewModel.CustomerId,
CustomerCode = customerViewModel.CustomerCode,
CustomerName = customerViewModel.CustomerName,
ContactPersonName = customerViewModel.ContactPersonName,
Designation = customerViewModel.Designation,
Email = customerViewModel.Email,
MobileNo = customerViewModel.MobileNo,
ContactNo = customerViewModel.ContactNo,
Fax = customerViewModel.Fax,
PrimaryAddress = customerViewModel.PrimaryAddress,
City = customerViewModel.City,
StateId = customerViewModel.StateId,
CountryId = customerViewModel.CountryId,
PinCode = customerViewModel.PinCode,
CSTNo = customerViewModel.CSTNo,
TINNo = customerViewModel.TINNo,
PANNo = customerViewModel.PANNo,
GSTNo = customerViewModel.GSTNo,
ExciseNo = customerViewModel.ExciseNo,
EmployeeId = customerViewModel.EmployeeId,
CustomerTypeId = customerViewModel.CustomerTypeId,
CompanyId = customerViewModel.CompanyId,
CreatedBy = customerViewModel.CreatedBy,
Status = customerViewModel.Customer_Status,
AnnualTurnover = customerViewModel.AnnualTurnover,
GST_Exempt = customerViewModel.GST_Exempt

int customerId = 0;
responseOut = dbInterface.AddEditCustomer(customer, out customerId);

if (responseOut.status == ActionStatus.Success)
if (customerBranchs != null && customerBranchs.Count > 0)
foreach (CustomerBranchViewModel customerBranchViewModel in customerBranchs)
CustomerBranch customerBranch = new CustomerBranch
CustomerId = customerId,
CustomerBranchId = customerBranchViewModel.CustomerBranchId,
BranchName = customerBranchViewModel.BranchName,
ContactPersonName = customerBranchViewModel.ContactPersonName,
Designation = customerBranchViewModel.Designation,
Email = customerBranchViewModel.Email,
MobileNo = customerBranchViewModel.MobileNo,
ContactNo = customerBranchViewModel.ContactNo,
Fax = customerBranchViewModel.Fax,
PrimaryAddress = customerBranchViewModel.PrimaryAddress,
City = customerBranchViewModel.City,
StateId = customerBranchViewModel.StateId,
CountryId = customerBranchViewModel.CountryId,
PinCode = customerBranchViewModel.PinCode,
CSTNo = customerBranchViewModel.CSTNo,
TINNo = customerBranchViewModel.TINNo,
PANNo = customerBranchViewModel.PANNo,
GSTNo = customerBranchViewModel.GSTNo,
AnnualTurnover = customerBranchViewModel.AnnualTurnover,
Status = true
responseOutBranch = dbInterface.AddEditCustomerBranch(customerBranch);
if (customerProducts != null && customerProducts.Count > 0)
foreach (CustomerProductViewModel customerProductViewModel in customerProducts)
CustomerProductMapping customerProduct = new CustomerProductMapping
CustomerId = customerId,
MappingId = customerProductViewModel.MappingId,
ProductId = customerProductViewModel.ProductId,
Status = true
responseOutProduct = dbInterface.AddEditCustomerProduct(customerProduct);
if(customerFollowUps!=null && customerFollowUps.Count>0)
foreach(CustomerFollowUpViewModel customerFollowUpViewModel in customerFollowUps)
CustomerFollowUp customerFollowUp = new CustomerFollowUp {

CustomerFollowUpId= customerFollowUpViewModel.CustomerFollowUpId,
CustomerId= customerId,
FollowUpActivityTypeId = customerFollowUpViewModel.FollowUpActivityTypeId,
FollowUpReminderDateTime= Convert.ToDateTime(customerFollowUpViewModel.FollowUpReminderDateTime),
FollowUpRemarks= customerFollowUpViewModel.FollowUpRemarks,
Priority= Convert.ToByte(customerFollowUpViewModel.Priority),
FollowUpStatusId= customerFollowUpViewModel.FollowUpStatusId,
FollowUpStatusReason= customerFollowUpViewModel.FollowUpStatusReason,
FollowUpByUserId= customerFollowUpViewModel.FollowUpByUserId,
CreatedBy= customerViewModel.CreatedBy,

responseOutFollowUp = dbInterface.AddEditCustomerFollowUp(customerFollowUp);


SL sl = new SL
SLId = 0,
SLCode = customerViewModel.CustomerCode,
SLHead = customerViewModel.CustomerName,
RefCode = customerViewModel.CustomerCode,
SLTypeId = 2,
CostCenterId = 0,
SubCostCenterId = 0,
CompanyId = customerViewModel.CompanyId,
CreatedBy = customerViewModel.CreatedBy,
Status = true

responseOutSL = dbInterface.AddEditCustomerSL(sl, customerViewModel.CustomerId == 0 ? “Add” : “Edit”);
catch (TransactionException ex1)
responseOut.status = ActionStatus.Fail;
responseOut.message = ActionMessage.ApplicationException;
Logger.SaveErrorLog(this.ToString(), MethodBase.GetCurrentMethod().Name, ex1);
throw ex1;
catch (Exception ex)
responseOut.status = ActionStatus.Fail;
responseOut.message = ActionMessage.ApplicationException;
Logger.SaveErrorLog(this.ToString(), MethodBase.GetCurrentMethod().Name, ex);
throw ex;
return responseOut;


Role based security in MVC application

As the name says provide users to access pages by there access levels security.

Here we will implement role-based security by Action filters so the question is the what is action filters in MVC if you don’t know about the actions filters so will brief it first.

Action Filters: MVC provides a feature to users to allow the filters when an action will be executing or after an action will be executed.
Action filters have two events:

1.On Action Executing
2.On Action Executed


Now come to Role-Based Security:

Step-1: Here we have an example of activity calendar management in HR module, so we want to implement role-based security on it


[ValidateRequest(true, UserInterfaceHelper.Add_Edit_ActivityCalender, (int)AccessMode.ViewAccess, (int)RequestMode.GetPost)]
public ActionResult AddEditActivityCalender(int activitycalenderId = 0, int accessMode = 3)

if (activitycalenderId != 0)

ViewData[“activitycalenderId”] = activitycalenderId;
ViewData[“accessMode”] = accessMode;
ViewData[“currentDate”] = DateTime.Now.ToString(“dd-MMM-yyyy”);
ViewData[“activitycalenderId”] = 0;
ViewData[“accessMode”] = 0;
ViewData[“currentDate”] = DateTime.Now.ToString(“dd-MMM-yyyy”);

catch (Exception ex)
Logger.SaveErrorLog(this.ToString(), MethodBase.GetCurrentMethod().Name, ex);
return View();

Here we have an action method AddEditActivityCalender here we have to implement ValidateRequest Filter for implementing Role-Based Security.

Step-2: How ValidateRequest works here

[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = false)]
public class ValidateRequest : FilterAttribute, IAuthorizationFilter
public ValidateRequest();
public ValidateRequest(bool isActive, int userInterfaceId, int accessMode = 3, int requestMode = 1);

public void OnAuthorization(AuthorizationContext filterContext);


more :