[英]Rest API post call with token & multipartform returns 401 error
I try to build a post request that contains form data content (file) and url.我尝试构建一个包含表单数据内容(文件)和 url 的发布请求。 the Url is built this way: http://base-url/api/endpoint?name=modelTest This call works perfectly fine in postman but it seems i can't reproduce it in C# code.
the Url is built this way: http://base-url/api/endpoint?name=modelTest This call works perfectly fine in postman but it seems i can't reproduce it in C# code.
My model object passed as param looks like this:我的 model object 作为参数传递如下所示:
modelRequest.Model = @"C:\Users\temp\myFile.txt";
Here is the problematic method:这是有问题的方法:
public async Task<ModelResponse> CreateModel(Uri url, ModelRequest modelRequest, string token)
{
HttpClient httpClient = new HttpClient();
using (var request = new HttpRequestMessage(new HttpMethod("POST"), url))
{
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
var multipartContent = new MultipartFormDataContent();
multipartContent.Add(new ByteArrayContent(
File.ReadAllBytes(modelRequest.Model)),
"model",
Path.GetFileName(modelRequest.Model));
request.Content = multipartContent;
var response = await httpClient.SendAsync(request);
string output = await response.Content.ReadAsStringAsync();
Console.WriteLine(JsonConvert.DeserializeObject(output));
ModelResponse returnValue = JsonConvert.DeserializeObject<ModelResponse>(output);
return returnValue;
}
I have a 401 response.我有一个 401 响应。 I even tried the generated code generated with Postman and I obtain the same issue.
我什至尝试了用 Postman 生成的生成代码,我得到了同样的问题。
The generated code by postman is the following: postman生成的代码如下:
var client = new RestClient("http://base-url/api/endpoint?name=modelTest");
client.Timeout = -1;
var request = new RestRequest(Method.POST);
request.AddHeader("Authorization", "Bearer {token}");
request.AddFile("model", @"C:\Users\temp\myFile.txt");
IRestResponse response = client.Execute(request);
Console.WriteLine(response.Content);
Try this.尝试这个。
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
instead of this而不是这个
request.Headers.TryAddWithoutValidation("Authorization", "Bearer " + token);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.