如何使用C#HttpClient向Web API提交文件和其他表单内容

时间:2018-02-06 13:02:52

标签: c# asp.net asp.net-web-api

我正在尝试使用C#中的HttpClient提交文件和一些 KeyValuePairs 。(在本例中为id)。 正在提交文件,但我无法阅读KeyValuePairs

这是我的控制器。

    [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();
        }

这是Api代码

[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");
        }

我能够读取该文件。它会被提交给API。问题是我作为keyvaluepair提交的“id”。我不知道怎么读。如果我将参数传递给Api。客户端返回错误“未找到”。

1 个答案:

答案 0 :(得分:0)

我终于能够读取我发送给Web API的文件和参数。这是对HttpContext.Current.Request

的一个简单的启示

这是我修改API代码的方式。

[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");
    }

通过使用 HttpContext.Current.Request.Params ,我能够从api中读取其他值。 Request.Files包含所有文件,Request.Params包含所有字符串参数。