Showing posts with label WebApi2. Show all posts
Showing posts with label WebApi2. Show all posts

http headers in webapi

Htttp Header:- Http Header is a field of an HTTP request or response that passes additional info about the request or response. For example, a request message can use headers to indicate it's preferred media formats, while a response can use header to indicate the media format of the returned body.


Request Headers:- Headers containing more information about the resource to be fetched or about the client itself or we can say that Http headers that have additional info about the request.Types of Request headers:- 

  • Accept
  • Accept-Encoding
  • Authorization 
  • Origin
  • Referer
  • User-Agent
  • If-Modified Since
  • If-None-Match
  • Cookie
  • Host


Response Headers:- Headers with additional information about the response, like its location or about the server itself (name, version, …). Types of Response Header:-

  • Pragma
  • Server
  • Set-Cookie
  • www-Authentication:- Basic,Bearer Token,Digest etc
  • x-Frame-options
  • Cache-Control
  • Location
  • Expire



Representation Header:- metadata about the resource in the message body (e.g. encoding, media type, etc.). 
OR
Http headers that additional info for both request and response but no relation with the data transmitted in the body . They are formely known as General headers.
  • Content-Type
  • Content-Encoding
  • Content-Length
  • Connection
  • Transfer-Encoding  

Fetch Metadata Request Header:- Headers with metadata about the resource in the message body (e.g. encoding, media type, etc.).

  • Sec-Fetch-Site
  • Sec-Fetch-Mode
  • Sec-Fetch-User
  • Sec-Fetch-Dest  

Note:-The current HTTP/1.1 specification no longer refers to entities, entity headers or entity-body. Some of the fields are now referred to as Representation headefields.


Difference between Accept header and Content-Type header

The Accept header attribute specifies the format of response data which the client expects.


GET /posts HTTP/1.1 

Accept:application/json 


GET /posts/42 HTTP/1.1 

             Accept: application/xml 


Content-Type header attribute specifies the format of the data in the request body so that receiver can parse it into appropriate format.


             ContentType: application/x-www-form-urlencoded

             ContentType: application/multipart/form-data

 



how to use automapper in webapi

 

AutoMapper:- AutoMapper is an object-object mapper. Object-object mapping works by transforming an input object of one type into an output object of a different type. What makes AutoMapper interesting is that it provides some interesting conventions to take the dirty work out of figuring out how to map type A to type B. As long as type B follows AutoMapper’s established convention, almost zero configuration is needed to map two types.


Step 1:- Create a web api project in visual studio 



Step 2:- Now create a table in Sql-Server and link this table to your application using DbFirst Approach.  


CREATE TABLE [dbo].[tblStudent](
       [Id] [int] IDENTITY(1,1) NOT NULL,
       [Name] [nvarchar](50) NULL,
       [DOB] [date] NULL,
       [Course] [nvarchar](50) NULL,
 CONSTRAINT [PK_tblStudent] PRIMARY KEY CLUSTERED
(
       [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
 
GO

 




Step 3:- Create a folder Dto in your Soultion folder and add a class file with StudentModel
namespace AutoMapper_InWebApi.Dto
{
    public class StudentModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string DOB { get; set; }
        public string Course { get; set; }
    }
}


Step 4:- Now install AutoMapper in your project soulution from menu bar in visual studio

 Tools>Nuget Package Manager>Manage Nuget Packages for solutions ,you can check automapper compatible version according to to your visual studio in Version dropdown in right side  





Step5:- Add a folder in Solution Helpers and add a class file with name ApplicationMapping.cs 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using AutoMapper;

using AutoMapper_InWebApi.Dto;

using AutoMapper_InWebApi.Models;

 

namespace AutoMapper_InWebApi.Helpers

{

    public class ApplicationMapping:Profile

    {

        public ApplicationMapping()

        {

            CreateMap<tblStudent, StudentModel>().ReverseMap();

        }

    }

}



Step 6:- Now Add a Empty Controller with name Students in Your Controller folder and Paste the following code in this Controller.cs file   

StudentsController.cs

using AutoMapper_InWebApi.Dto;

using AutoMapper_InWebApi.Models;

using System.Collections.Generic;

using System.Linq;

using System.Net;

using System.Web.Http;

using AutoMapper;

 

namespace AutoMapper_InWebApi.Controllers

{

    public class StudentsController : ApiController

    {

        BlogDatabaseEntities _context = new BlogDatabaseEntities();

 

        public IEnumerable<StudentModel> GetStudents()

        {

            var students = _context.tblStudent.ToList().Select(Mapper.Map<tblStudent,StudentModel>);

            return students;

        }

 

        public StudentModel GetStudentById(int id)

        {

            var student = _context.tblStudent.SingleOrDefault(c => c.Id == id);

            if (student == null)

                throw new HttpResponseException(HttpStatusCode.BadRequest);

            return Mapper.Map<tblStudent,StudentModel>(student);

        }

 

       

        public StudentModel PostStudent(StudentModel model)

        {

            if (!ModelState.IsValid)

                throw new HttpResponseException(HttpStatusCode.BadRequest);

 

            var student = Mapper.Map<StudentModel, tblStudent>(model);

            _context.tblStudent.Add(student);

            _context.SaveChanges();

            model.Id = student.Id;

            return model;

        }

 

    }

}


Step7:- Now run your and check it in Postman or fiddler 

 



 

how to upload a file in webapi


Step 1:- Create a WebApi Project in Visual Studio with Name FileUploadInWebApi. 

Step 2:- Add a Controller name with FileUploading in Controller Folder in your project and paste the following code. 


using System;

using System.IO;

using System.Net.Http;

using System.Threading.Tasks;

using System.Web;

using System.Web.Http;

 

namespace FileUploadInWebAPI.Controllers

{

    public class FileUploadingController : ApiController

    {

        [HttpPost]

        [Route("api/fileuploading/uploadfile")]

        public async Task<string> UploadFile()

        {

            var ctx = HttpContext.Current;

            var root = ctx.Server.MapPath("~/App_Data");

            var provider = new MultipartFormDataStreamProvider(root);

            try

            {

               await Request.Content.ReadAsMultipartAsync(provider);

               foreach(var file in provider.FileData)

                {

                    var name = file.Headers.ContentDisposition.FileName;

                    name = name.Trim('"');

 

                    var localFileName = file.LocalFileName;

                    var filePath = Path.Combine(root, name);

                    File.Move(localFileName, filePath);

                }

            }

            catch (Exception ex)

            {

                return $"Error:{ex.Message}";

            }   

            return "File Uploaded";

        }

    }

}


Step 3:- Run your project and paste this "api/fileuploading/uploadfile" line in Postman url option and select Post Request ,then click on form-data and select file from right, now upload a file. Now click on send.

Step 4:- Check image or file in App_Data folder.   

 




Crud Operation In WebApi Using CodeFirst Approach

Basic Crud Operation In WebApi With CodeFirst 

Here we create a Crud Application in WebApi with Entityframework CodeFirst and will use Scaffolding for generate code for crud operation. 

Scaffolding is a Code generation framework for CRUD operations in MVC and WebAPI.

  Step 1:- Create a Project


Step 2:- Create a Model Class with name Student in model folder in your solution directory. 



 Step 3:- Create a another classs with name App_Context in Model folder.




Step 4:- Connect the application to database using Connection String.



    Step 5:- Add Controller class with option Controller with action using entity framework it will 
generate crud method using scaffolding.






Contoller Class Code :-

using System;

using System.Collections.Generic;

using System.Data;

using System.Data.Entity;

using System.Data.Entity.Infrastructure;

using System.Linq;

using System.Net;

using System.Net.Http;

using System.Web.Http;

using System.Web.Http.Description;

using crudin_api_withcodefirst.Models;

 

namespace crudin_api_withcodefirst.Controllers

{

    public class StudentController : ApiController

    {

        private AppContext db = new AppContext();

 

        // GET: api/Student

        public IQueryable<Student> GetStudent()

        {

            return db.Student;

        }

 

        // GET: api/Student/5

        [ResponseType(typeof(Student))]

        public IHttpActionResult GetStudent(int id)

        {

            Student student = db.Student.Find(id);

            if (student == null)

            {

                return NotFound();

            }

 

            return Ok(student);

        }

 

        // PUT: api/Student/5

        [ResponseType(typeof(void))]

        public IHttpActionResult PutStudent(int id, Student student)

        {

            if (!ModelState.IsValid)

            {

                return BadRequest(ModelState);

            }

 

            if (id != student.Id)

            {

                return BadRequest();

            }

 

            db.Entry(student).State = EntityState.Modified;

 

            try

            {

                db.SaveChanges();

            }

            catch (DbUpdateConcurrencyException)

            {

                if (!StudentExists(id))

                {

                    return NotFound();

                }

                else

                {

                    throw;

                }

            }

 

            return StatusCode(HttpStatusCode.NoContent);

        }

 

        // POST: api/Student

        [ResponseType(typeof(Student))]

        public IHttpActionResult PostStudent(Student student)

        {

            if (!ModelState.IsValid)

            {

                return BadRequest(ModelState);

            }

 

            db.Student.Add(student);

            db.SaveChanges();

 

            return CreatedAtRoute("DefaultApi", new { id = student.Id }, student);

        }

 

        // DELETE: api/Student/5

        [ResponseType(typeof(Student))]

        public IHttpActionResult DeleteStudent(int id)

        {

            Student student = db.Student.Find(id);

            if (student == null)

            {

                return NotFound();

            }

 

            db.Student.Remove(student);

            db.SaveChanges();

 

            return Ok(student);

        }

 

        protected override void Dispose(bool disposing)

        {

            if (disposing)

            {

                db.Dispose();

            }

            base.Dispose(disposing);

        }

 

        private bool StudentExists(int id)

        {

            return db.Student.Count(e => e.Id == id) > 0;

        }

    }

}


      Step 6:- Now run your application and Check ur crud in any api testing app Post,Fiddler.