Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8161959
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 6, 20262026-06-06T18:36:31+00:00 2026-06-06T18:36:31+00:00

I have an ASP.NET MVC 3 controller action. That action is defined as follows:

  • 0

I have an ASP.NET MVC 3 controller action. That action is defined as follows:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(string parameter1, HttpPostedFileBase uploadFile)
{
  if (parameter1 == null)
    return Json(new { status = "Error" }, JsonRequestBehavior.AllowGet);

  if (uploadFile.ContentLength == 0)
    return Json(new { status = "Error" }, JsonRequestBehavior.AllowGet);

  return Json(new { status = "Success" }, JsonRequestBehavior.AllowGet);
}

I need to upload to this endpoint via a C# app. Currently, I’m using the following:

public void Upload()
{
  WebRequest request = HttpWebRequest.Create("http://www.mydomain.com/myendpoint");
  request.Method = "POST";
  request.ContentType = "multipart/form-data";
  request.BeginGetRequestStream(new AsyncCallback(UploadBeginGetRequestStreamCallBack), request);
}

private void UploadBeginGetRequestStreamCallBack(IAsyncResult ar)
{
  string json = "{\"parameter1\":\"test\"}";

  HttpWebRequest webRequest = (HttpWebRequest)(ar.AsyncState);
  using (Stream postStream = webRequest.EndGetRequestStream(ar))
  {
    byte[] byteArray = Encoding.UTF8.GetBytes(json);
    postStream.Write(byteArray, 0, byteArray.Length);
    postStream.Close();
  }
  webRequest.BeginGetResponse(new AsyncCallback(Upload_Completed), webRequest);
}

private void Upload_Completed(IAsyncResult result)
{
  WebRequest request = (WebRequest)(result.AsyncState);
  WebResponse response = request.EndGetResponse(result);
  // Parse response
}

While I get a 200, the status is always “Error”. After digging further, I noticed that parameter1 is always null. I’m slightly confused. Can somebody please tell me how to programmatically send data for parameter1 as well as a file from code via a WebRequest?

Thank you!

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-06T18:36:32+00:00Added an answer on June 6, 2026 at 6:36 pm

    Dude, this one was difficult!

    I really tried to find a way to programmatically upload files to a MVC action, but I couldn’t, I’m sorry.
    The solution I found converts the file to a byte array and serializes it into a string.

    Here, take a look.

    This is your controller action:

        [AcceptVerbs(HttpVerbs.Post)]
                public ActionResult uploadFile(string fileName, string fileBytes)
                {
                    if (string.IsNullOrEmpty(fileName) || string.IsNullOrEmpty(fileBytes))
                        return Json(new { status = "Error" }, JsonRequestBehavior.AllowGet);
        
                    string[] byteToConvert = fileBytes.Split('.');
                    List<byte> fileBytesList = new List<byte>();
        byteToConvert.ToList<string>()
                .Where(x => !string.IsNullOrEmpty(x))
                .ToList<string>()
                .ForEach(x => fileBytesList.Add(Convert.ToByte(x)));
        
                    //Now you can save the bytes list to a file
                    
                    return Json(new { status = "Success" }, JsonRequestBehavior.AllowGet);
                }
    

    And this is the client code (who posts the file):

    public void Upload()
            {
                WebRequest request = HttpWebRequest.Create("http://localhost:7267/Search/uploadFile");
                request.Method = "POST";
                //This is important, MVC uses the content-type to discover the action parameters
                request.ContentType = "application/x-www-form-urlencoded";
    
                byte[] fileBytes = System.IO.File.ReadAllBytes(@"C:\myFile.jpg");
    
                StringBuilder serializedBytes = new StringBuilder();
                
                //Let's serialize the bytes of your file
                fileBytes.ToList<byte>().ForEach(x => serializedBytes.AppendFormat("{0}.", Convert.ToUInt32(x)));
    
                string postParameters = String.Format("fileName={0}&fileBytes={1}", "myFile.jpg", serializedBytes.ToString());
    
                byte[] postData = Encoding.UTF8.GetBytes(postParameters);
                
                using (Stream postStream = request.GetRequestStream())
                {
                    postStream.Write(postData, 0, postData.Length);
                    postStream.Close();
                }
    
                request.BeginGetResponse(new AsyncCallback(Upload_Completed), request);
            }
    
            private void Upload_Completed(IAsyncResult result)
            {
                WebRequest request = (WebRequest)(result.AsyncState);
                WebResponse response = request.EndGetResponse(result);
                // Parse response
            }
    

    Hanselman has a good post regarding file upload from a web interface, which is not your case.

    If you need help to convert the byte array back to a file, check this thread: Can a Byte[] Array be written to a file in C#?

    Hope this helps.

    If anyone has a better solution, I’d like to take a look at it.

    Regards,
    Calil

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have an ASP.NET MVC 3 Controller Action that accepts an object as follows:
In ASP.NET MVC I have a controller that looks somehow like this: public class
If I have an ASP.NET MVC controller action that is called from a jQuery
I have an ASP.Net MVC Controller with a 'MapColumns' action along with a corresponding
ASP.Net MVC Controllers have several methods of forwarding control to another controller or action.
I have a route defined last in my ASP.Net MVC 2 app that will
Let's say I have a controller action defined as: public ActionResult(MyModel model, string someParameter)
I have an asp.net mvc application with a route similar to: routes.MapRoute(Blog, {controller}/{action}/{year}/{month}/{day}/{friendlyName}, new
I am writing application with asp.net mvc. I have controller with action, which use
I have an Asp.Net MVC application that works in the vs.net development web server.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.