C#RestSharp和ASP .NET Web API - 上传json和文件

时间:2017-01-05 05:19:49

标签: c# asp.net-web-api json.net image-uploading restsharp

问题: 如何组织在RestSharp中发送JSON和文件?以及如何获取服务器上的数据?

protected override void SaveDoWork(object sender, DoWorkEventArgs e)
{
    IRestResponse response;
    Meta meta = e.Argument as Meta;

    var json = JsonConvert.SerializeObject(meta, new JsonSerializerSettings() { TypeNameHandling = TypeNameHandling.Objects });
    var request = new RestRequest("api/v1/persons/save", Method.POST);

    request.AddHeader("Charset", "utf-8");
    request.AddHeader("Content-Type", "multipart/form-data");

    request.AddParameter("application/json", json, ParameterType.RequestBody);

    using (var stream = new System.IO.MemoryStream())
    {
        if (meta.Person.PersonPhotoFrontView != null)
        {
            meta.Person.PersonPhotoFrontView.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg);
            request.AddFileBytes("PersonPhoto", stream.ToArray(), "PersonPhotoFrontView");
        }
    }


    response = this._client.Execute(request);
    if (response.ErrorException == null)
    {                

    }
    else
    {

    }
}

服务器端:在服务器端,一切都非常简单。有必要单独处理JSON和接收的文件:

        [HttpPost, Route("save")]
        public object Save([FromBody] JObject meta)
        {
            Meta metaData = meta.ToObject<Meta>();

            if (metaData != null)
            {
                if (_personModel.Save(metaData, HttpContext.Current.Request))
                {

                    return new Notification("OK");
                }

            }

            return new Notification("Fail");
        }

发送后,我收到错误消息:

{
    "Message": "Media Type \"multipart/form-data\" request entity for this resource is not supported",
    "ExceptionMessage": "There are no available MediaTypeFormatter read object type \"JObject\" with the contents of media type \"multipart/form-data\".",
    "ExceptionType": "System.Net.Http.UnsupportedMediaTypeException",
    "StackTrace": "   в System.Net.Http.HttpContentExtensions.ReadAsAsync[T](HttpContent content, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)rn   в System.Web.Http.ModelBinding.FormatterParameterBinding.ReadContentAsync(HttpRequestMessage request, Type type, IEnumerable`1 formatters, IFormatterLogger formatterLogger, CancellationToken cancellationToken)"
}

0 个答案:

没有答案