Restsharp posting file and model data to web api

Restsharp posting file and model data to web api



WebApiConfig .cs

In order to add support for multipart/form-data we need to add below line to webapi.config

config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Http;

namespace RestSharpEx
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services

            // Web API routes
            config.MapHttpAttributeRoutes();
            config.Formatters.XmlFormatter.SupportedMediaTypes.Add(new System.Net.Http.Headers.MediaTypeHeaderValue("multipart/form-data"));
            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );
        }
    }
}



MyApiController.cs


using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http;
using Newtonsoft.Json;
using RestSharpEx.Models;

public class MyApiController : ApiController
    {
  [HttpPost, Route("api/MyApi/BulkUploadFile")]
        public void BulkUploadFile(FileUploadModel model)
        {
            HttpResponseMessage result = null;
            var httpRequest = HttpContext.Current.Request;
            //Access your variable using
            var me = JsonConvert.DeserializeObject<FileUploadModel>((HttpContext.Current.Request.Params["model"]).ToString());
            if (httpRequest.Files.Count > 0)
            {
                var docfiles = new List<string>();
                foreach (string file in httpRequest.Files)
                {
                    var postedFile = httpRequest.Files[file];
                    var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
                    postedFile.SaveAs(filePath);
                    docfiles.Add(filePath);
                }
                result = Request.CreateResponse(HttpStatusCode.Created, docfiles);
            }
        }
}
Below line will be used to bring information of posted model as web api dont support it. Cant be sent as a body parameter.
//Access your variable using
            var me = JsonConvert.DeserializeObject<FileUploadModel>((HttpContext.Current.Request.Params["model"]).ToString());



Mvc controller action


[HttpPost]
        public ActionResult PostWithFile(FileUploadModel model)
        {
            if (Request.Files.Count > 0)
            {
                var file = Request.Files[0];

                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Images/"), fileName);
                    file.SaveAs(path);
                    var apiUrl = @"http://localhost:8076/api/MyApi/BulkUploadFile";
                    var client = new RestClient(apiUrl);
                    //if (!string.IsNullOrWhiteSpace(userName))
                    //{
                    //    client.Authenticator = new HttpBasicAuthenticator(userName, password);
                    //}
                    client.ClearHandlers();
                    //var jsonDeserializer = new JsonDeserializer();
                    //client.AddHandler("application/json", jsonDeserializer);
                    var request = new RestRequest(Method.POST);
                    request.AddHeader("Accept", "application/json");
                    request.Parameters.Clear();
                    request.AddParameter("model", JsonConvert.SerializeObject(model));
                    request.AddHeader("Content-Type", "multipart/form-data");
                    request.AddFile("content", path);
                    var result = client.Execute(request).Content;
                    var finalResult = JsonConvert.DeserializeObject<FileUploadModel>(result);
                }

            }
            return View(model);
        }

Below line is important

request.AddParameter("model", JsonConvert.SerializeObject(model));
                    request.AddHeader("Content-Type", "multipart/form-data");
                    request.AddFile("content", path);

As we are defining it as multipart/form-data and then adding model as a parameter and also adding a file to request using path.


View.cshtml


@model RestSharpEx.Models.FileUploadModel

@{
    ViewBag.Title = "PostWithFile";
}

<h2>PostWithFile</h2>


@*@using (Html.BeginForm())*@
    @using (Html.BeginForm("PostWithFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>FileUploadModel</h4>
        <hr />
        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
        <div class="form-group">
            @Html.LabelFor(model => model.FileId, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FileId, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FileId, "", new { @class = "text-danger" })
            </div>
        </div>

        <div class="form-group">
            @Html.LabelFor(model => model.FileDescription, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.EditorFor(model => model.FileDescription, new { htmlAttributes = new { @class = "form-control" } })
                @Html.ValidationMessageFor(model => model.FileDescription, "", new { @class = "text-danger" })
            </div>
        </div>
        <div class="form-group">
            @Html.LabelFor(model => model.FileDescription, htmlAttributes: new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                <input type="file" name="file" />
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input type="submit" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}

<div>
    @Html.ActionLink("Back to List", "Index")
</div>

@section Scripts {
    @Scripts.Render("~/bundles/jqueryval")
}

Note : We need to use     @using (Html.BeginForm("PostWithFile", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))

in begin form in order to send to model with file upload data.

Share on Google Plus

About myzingonline

Myzingonline is all about zing to share experience, knowledge, likes, dislikes and ideas of a person to the world.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment