c# – 发布文件以及web api的一些参数

c# – 发布文件以及web api的一些参数,第1张

概述我有Web api控制器Uploads Controller,它有PostUpload方法将数据存储到数据库. 现在我试图将文件和一些参数发布到那个web api但是所有的尝试都失败了,就像传递数组列表,json对象一样,我们不能将文件和参数发布到web api? var request = new RestRequest("Uploads", Method.POST);request.Requ 我有Web API控制器Uploads Controller,它有PostUpload方法将数据存储到数据库.

现在我试图将文件和一些参数发布到那个web API但是所有的尝试都失败了,就像传递数组列表,Json对象一样,我们不能将文件和参数发布到web 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","image/png");request.AddParameter("participantsID",2);request.AddParameter("taskID",77);request.AddParameter("EnteredAnswerOptionID",235);IRestResponse response = createClIEnt().Execute(request);

web 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

我需要将文件和参数发布到我的API.

使用restsharp发送数据

解决方法 我能够使用以下控制台应用程序成功发布(基于 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/Stackoverflow/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>();        }    }
总结

以上是内存溢出为你收集整理的c# – 发布文件以及web api的一些参数全部内容,希望文章能够帮你解决c# – 发布文件以及web api的一些参数所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/1226942.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-05
下一篇 2022-06-05

发表评论

登录后才能评论

评论列表(0条)

保存