我正在尝试使用 restClient (RestSharp)请求从c#类上传文件. 我正在创建Method.POST方法,并将一个音频文件作为multipart/form-data添加到此请求.
I am trying to upload files from the c# class using restClient (RestSharp) request. I am creating Method.POST method and add one Audio file to this request As multipart/form-data.
我执行请求时服务器抛出异常.
Server throws an exception when I execute the request.
例外:
System.ArgumentNullException: Value cannot be null. Parameter name: value at System.Enum.TryParseEnum(Type enumType, String value, Boolean ignoreCase, EnumResult& parseResult) at System.Enum.Parse(Type enumType, String value, Boolean ignoreCase) at Groove.Libraries.Helper.EnumHelper.ParseEnum[T](String value) in D:\project\Groove\Web\Groove\Libraries\Helper\EnumHelper.cs:line 47 at Groove.Controllers.Api.DocumentController. <PostDocumentUpload>d__5.MoveNext()RestClient请求代码:
RestClient Request Code :
string api_url = "localhost:57997/"; var fullFileName = "Adios.mp3"; var filepath = @"C:\Users\Admin\Desktop\Adios.mp3"; RestClient client = new RestClient(ApiModel.api_url); var request = new RestRequest("api/document", Method.POST); request.AddFile(Path.GetFileNameWithoutExtension(fullFileName), filepath); request.AddHeader("Content-Type", "multipart/form-data"); request.AddParameter("ReferenceType",28,ParameterType.RequestBody); IRestResponse response = client.Execute(request);服务器代码:
public async Task<object> PostDocumentUpload() { try { // Make temp physical path where file to be saved var tempPath = HttpContext.Current.Server.MapPath(string.Format("{0}/{1}", Constants.MediaResourceFolder, Constants.MediaResorceTempFolder)); // Check temporary path is exist or not, if not then create temporary folder if (!Directory.Exists(tempPath)) { Directory.CreateDirectory(tempPath); } // Create object of MyMultipartFormDataStreamProvider class var stream = new MultipartHelper(tempPath); // Save file at temp path await RequestContext.Request.Content.ReadAsMultipartAsync(stream); // Exception throw from Here, ReferenceType referenceType = EnumHelper.ParseEnum<ReferenceType>(stream.FormData["ReferenceType"]); // -------------other code } catch (Exception ex) { return FailureResponse(ex); }我想问题是从请求中未正确设置stream.FormData ["ReferenceType"].
I guess problem is that stream.FormData["ReferenceType"] is not set correctly from request.
我不想更改服务器代码.因为当您从邮递员或浏览器打电话时,它工作正常.
I don't want change the server code. because it working fine when you call from postman or browser.
有人可以帮忙吗?谢谢
推荐答案我通过更改一些代码就找到了解决方案.
I found the solution by just changing the few codes.
更新的代码:
var request = new RestRequest("api/document", Method.POST); request.AddFile(Path.GetFileNameWithoutExtension(fullFileName), filepath); request.AddParameter("ReferenceType", ReferenceType.ToString()); request.AddParameter("RefId", StudioEventEntryId.ToString()); request.AlwaysMultipartFormData = true; IRestResponse response = client.Execute(request);更多推荐
在C#中使用RestClient作为multipart/form
发布评论