Search This Blog

Saturday, 8 December 2018

Adding Swagger to ASP.NET Web API

Step 1: - Open Visual Studio 2015 => Go to File Menu => New => Project...

Step 2: - In the Installed Templates list, select Visual C# => Web

Step 3: - Select ASP.Net Web Application (.NET Framework) from the Web list => Type SwaggerDemo in the Name box and click OK

Step 4: - Select Empty template from ASP.NET Templates List and Check Web API check box under Add folders and core references for:






























Step 5: - Right Click on Controllers folder => Add => Controller... => Select Web API Controller - Empty => Click Add => Type DefaultController in Controller Name box => Click Add




























Copy Past following code in DefaultController

/// <summary>
/// I'm Action1
/// </summary>
/// <returns>I'm Action1</returns>
[HttpGet]
public HttpResponseMessage Action1()
{
    return Request.CreateResponse(HttpStatusCode.OK, "I'm Action1");
}
/// <summary>
/// I'm Action2
/// </summary>
/// <returns>I'm Action2</returns>
[HttpGet]
public HttpResponseMessage Action2()
{
    return Request.CreateResponse(HttpStatusCode.OK, "I'm Action2");
}
/// <summary>
/// I'm Action3
/// </summary>
/// <returns>I'm Action3</returns>
[HttpGet]
public HttpResponseMessage Action3()
{
    return Request.CreateResponse(HttpStatusCode.OK, "I'm Action3");
}

Step 6: - Right click on References => Click on Manage NuGet Packages... => Click on Browse => Search "Swagger" => Select "Swashbuckle" from result => Click on Install























Step 7: - Open/Expand App_Start folder => Open SwaggerConfig.cs file => Add following line to enable Xml Comments description in swagger documentation

c.IncludeXmlComments(String.Format(@"{0}\bin\SwaggerDemo.XML", AppDomain.CurrentDomain.BaseDirectory));






















Step 8: - Right Click on Project Root folder => Click on Properties => Select "Build" => Under Output section Check checkbox "XML documentation file:" => Press Ctrl + S to save file























Step 9: - Open/Expand App_Start folder => Open WebApiConfig.cs file => Change following line 

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

To

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

All Done

Run Project

Step 10: - Enter swagger at the end of URL and Click on Enter






Tuesday, 27 November 2018

Call one web api from another web api in c#


Step 1: - Create WebApi 1 project

Step 2: - Copy Past following code in Controller Action

using System.Net.Http;

[HttpGet]
public HttpResponseMessage Test1(string value)
{
    return Request.CreateResponse(HttpStatusCode.OK, "You pass the value is : " + value);
}

[HttpPost]
public Author Test2(Author value)
{
    value.Status = "OK";

    return value;
}

Step 3: - Create Author Class in Models folder

public class Author
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string Status { get; set; }
}

Step 4: - Open WebApiConfig.cs and Add {action} in routeTemplate

public static void Register(HttpConfiguration config)
{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional });
}

Step 5: - Create WebApi 2 project

Step 6: - Copy Past following code in Controller Action


using System.Net.Http;

[HttpGet]
public string Test1(string value)
{
    string responseString = string.Empty;

    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:65346/");//WebApi 1 project URL
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        var response = client.GetAsync("api/default/Test1/?value=" + value + "").Result;
        if (response.IsSuccessStatusCode)
        {
            responseString = response.Content.ReadAsStringAsync().Result;
        }
    }
    return responseString;
}

[HttpPost]
public Author Test2(Author value)
{
    string responseString = string.Empty;
    Author objAuthor = new Author();
    using (var client = new HttpClient())
    {
        client.BaseAddress = new Uri("http://localhost:65346/");//WebApi 1 project URL
        client.DefaultRequestHeaders.Accept.Clear();
        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
        StringContent content = new StringContent(JsonConvert.SerializeObject(value), Encoding.UTF8, "application/json");
        var response = client.PostAsync("api/default/Test2", content).Result;
        if (response.IsSuccessStatusCode)
        {
            responseString = response.Content.ReadAsStringAsync().Result;
            objAuthor = response.Content.ReadAsAsync<Author>().Result;
        }
    }
    return objAuthor;
}

Step 7: - Create Author Class in Models folder

public class Author
{
    public int Id { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address { get; set; }
    public string Status { get; set; }
}


Step 8: - Open WebApiConfig.cs and Add {action} in routeTemplate

public static void Register(HttpConfiguration config)

{
    // Web API configuration and services

    // Web API routes
    config.MapHttpAttributeRoutes();

    config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{action}/{id}",
    defaults: new { id = RouteParameter.Optional });
}

Step 9: - Run both the project one by one

Step 10: - Use Postman to test WebApi 2 project

Note: - Copy URL of WebApi 1 project and change BaseAddress of WebApi 2 project

Step 11: - (GET Request) Copy Past URL (http://localhost:49317/api/default/test1?value=123) in Postman and Click Send button

Step 12: - (POST Request) Copy Past URL (http://localhost:49317/api/default/test2) in Postman and Copy Past following Json to Request body and Click Send button

Json
{
"Id":1,
"FirstName":"Ram",
"LastName":"G",
"Address":"Malad"
}