2

I am trying to submit a file with some KeyValuePairs.(which is id in this case) using HttpClient in C#. the File is being submitted but i cannot read the KeyValuePairs

This is my controller.

    [HttpPost]
        public async Task<ActionResult> Index(HttpPostedFileBase File)
        {
            HttpClient client = new HttpClient();
            client.BaseAddress = new Uri("http://localhost:65211/");
            MultipartFormDataContent form = new MultipartFormDataContent();
    //Here I am adding a file to a form
            HttpContent content = new StringContent("fileToUpload");
            form.Add(content, "fileToUpload");
            var stream = File.InputStream;
            content = new StreamContent(stream);
            content.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
            {
                Name = "fileToUpload",
                FileName = File.FileName
            };
            form.Add(content);
    // and here i am adding a dictionary with one keyvaluepair 
            Dictionary<string, string> Parameters = new Dictionary<string, string>();
            Parameters.Add("id", "3");
            form.Add(new FormUrlEncodedContent(Parameters));
    //this will hit the api         
   var response = await client.PostAsync("/api/Upload", form);
            var k = response.Content.ReadAsStringAsync().Result;
            return View();
        }

This is the Api Code

[Route("api/Upload")]
        [HttpPost]
       // i have tested public async Task<HttpResponseMessage> Upload(string id) <= giving parameters. the api doesnt hit if i give any
        public async Task<HttpResponseMessage> Upload()
        {
            var request = HttpContext.Current.Request;
            HttpResponseMessage result = null;    
            if (request.Files.Count == 0)
            {
                result = Request.CreateResponse(HttpStatusCode.OK, "Ok");;
            }
            var postedFile = request.Files[0];
            return Request.CreateResponse(HttpStatusCode.OK, "Ok");
        }

I am able to read the file. It gets submitted to the API. the problem is the "id" that i submitted as a keyvaluepair. I don't know how to read it. If i pass parameters to the Api. client returns the error "Not Found".

2
  • Try adding a parameter to your route and pass it through the call URL [Route("api/Upload/{id}")], public async Task<HttpResponseMessage> Upload(string id), var response = await client.PostAsync($"/api/Upload/{id}", form); Commented Feb 6, 2018 at 13:13
  • that does not work. breakpoint never hits on api and the response is 404 not found. Commented Feb 7, 2018 at 5:27

1 Answer 1

1

I finally was able to read both the file and the parameters I sent to the Web API. It was a simple implimentation with HttpContext.Current.Request

This is how i modified the API code.

[Route("api/Upload")]
    [HttpPost]
   // i have tested public async Task<HttpResponseMessage> Upload(string id) <= giving parameters. the api doesnt hit if i give any
    public async Task<HttpResponseMessage> Upload()
    {
        var request = HttpContext.Current.Request;
        var key = Request.Params["key"]; // **<- LOOK AT THIS HERE**
        HttpResponseMessage result = null;    
        if (request.Files.Count == 0)
        {
            result = Request.CreateResponse(HttpStatusCode.OK, "Ok");;
        }
        var postedFile = request.Files[0];
        return Request.CreateResponse(HttpStatusCode.OK, "Ok");
    }

By using HttpContext.Current.Request.Params, I was able to read the other values from the api. Request.Files contains all the files and Request.Params contains all string parameters.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.