Post 文件以及网络的一些参数 api

Post file as well as some parameter to web api

我有 Web api 控制器上传控制器,它有 PostUpload 方法将数据存储到数据库。

现在我正在尝试 post 文件和该 Web 的一些参数 api 但是所有尝试都失败了,比如通过数组列表,json 对象,我们不能post 文件和网络参数 api?

var request = new RestRequest("Uploads", Method.POST);
request.RequestFormat = DataFormat.Json;

request.AddHeader("Content-Type", "application/json");
request.AddFile("filename", Server.MapPath("/Images/137549014628194.R6MyHlYrIfIo3BWPIytG_height640.png"), "image/png");
request.AddFile("filename", Server.MapPath("/Images/137549014628194.R6MyHlYrIfIo3BWPIytG_height640.png"), "image/png");
request.AddFile("filename", Server.MapPath("/Images/137549014628194.R6MyHlYrIfIo3BWPIytG_height640.png"), "image/png");
request.AddParameter("participantsId", 2);
request.AddParameter("taskId", 77);
request.AddParameter("EnteredAnswerOptionId", 235);
IRestResponse response = createClient().Execute(request);

网络api方法:

[HttpPost]
public string PostUpload(int? participantsId, int? taskId, int? EnteredAnswerOptionId)
{
    var file = HttpContext.Current.Request.Files.Count > 0 ?
    HttpContext.Current.Request.Files[0] : null;
    if (file.ContentLength > 0)
    {
        var fileName = Path.GetFileName(file.FileName);
        var path = Path.Combine(HttpContext.Current.Server.MapPath("~/uploads"), fileName);
        file.SaveAs(path); 
    }
    return "/uploads/" + file.FileName;
}

但它给出如下错误:

ExceptionMessage":"No MediaTypeFormatter is available to read an object of type 'xxxx' from content with media type 'multipart/form-data

我需要 post 文件以及我 api 的参数。

使用 restsharp 发送数据

我能够post成功使用以下控制台应用程序(基于this post):

    static void Main(string[] args)
    {
        RunAsync().Wait();
    }

    static async Task RunAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri("http://localhost:3963/");
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            string filepath = "C:/Users/Popper/Desktop/Whosebug/MatchPositions.PNG";
            string filename = "MatchPositions.PNG";

            MultipartFormDataContent content = new MultipartFormDataContent();
            ByteArrayContent fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(filepath));
            fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") { FileName = filename };
            content.Add(fileContent);

            HttpResponseMessage response = await client.PostAsync("api/Upload?participantsId=2&taskId=77&EnteredAnswerOptionId=235", content);
            string returnString = await response.Content.ReadAsAsync<string>();
        }
    }