简体   繁体   English

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

[英]How to submit a file and some other form content to Web API using C# HttpClient

I am trying to submit a file with some KeyValuePairs .(which is id in this case) using HttpClient in C#.我正在尝试使用 C# 中的 HttpClient 提交一个带有一些KeyValuePairs文件(在这种情况下是 id)。 the File is being submitted but i cannot read the KeyValuePairs文件正在提交,但我无法读取 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这是 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");
        }

I am able to read the file.我能够读取文件。 It gets submitted to the API.它被提交给 API。 the problem is the "id" that i submitted as a keyvaluepair.问题是我作为键值对提交的“id”。 I don't know how to read it.我不知道怎么读。 If i pass parameters to the Api.如果我将参数传递给 Api。 client returns the error "Not Found".客户端返回错误“未找到”。

I finally was able to read both the file and the parameters I sent to the Web API.我终于能够读取我发送到 Web API 的文件和参数。 It was a simple implimentation with HttpContext.Current.Request这是 HttpContext.Current.Request 的简单实现

This is how i modified the API code.这就是我修改 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");
    }

By using HttpContext.Current.Request.Params , I was able to read the other values from the api.通过使用HttpContext.Current.Request.Params ,我能够从 api 读取其他值。 Request.Files contains all the files and Request.Params contains all string parameters. Request.Files 包含所有文件,Request.Params 包含所有字符串参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM