0

我尝试调用外部 api,当我使用 Postman 时,它正在工作并返回值如下:

发布到 URL: https ://test.com/api/v1/users/check

数据原始杰森发布:

 { 
  "access_token":"4444-EA444B6-2844C7-A09C-44B05CA78E42A3", 
  "email":"test@test.com", 
  "create_user": true, 
  "first_name": "test4", 
  "last_name": "test", 
  "phone": 3104054512 
  } 

所以这是工作并返回我的响应模型。

但是当尝试使用此代码调用 api 时:

控制器:

     [Route("CreateUser")]
    public Task<UserReturn> CreateUser([FromBody] User user)
    {

        return  homebirdRepository.CreateUser(user);
    }



 public async Task<UserReturn> CreateUser(User userCheck)
    {
        using (GetWSObject<UserReturn> addObjectInt = new GetWSObject<UserReturn>())
        {
            return await addObjectInt.PostWSObjectModel("api/v1/users/check", userCheck, "API_URI");
        }
    }






    public async Task<T> PostWSObjectModel(string uriActionString, Object model, string apiKey)
    {
        T returnValue = default(T);

        try
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(WebConfigurationManager.AppSettings[apiKey]);
                var content = new StringContent(JsonConvert.SerializeObject(model));
                content.Headers.ContentType = new MediaTypeHeaderValue("application/json");
                HttpResponseMessage response = await client.PostAsync(uriActionString, content);
                response.EnsureSuccessStatusCode();


                var test = response.Content.ReadAsStringAsync().Result;


                returnValue = JsonConvert.DeserializeObject<T>(((HttpResponseMessage)response).Content.ReadAsStringAsync().Result);
            }

            return returnValue;
        }
        catch (Exception e)
        {
            throw (e);
        }
    }

此代码向我返回此错误:

   StatusCode: 401, ReasonPhrase: 'Unauthorized', Version: 1.1, Content: 
 System.Net.Http.StreamContent, 
   Headers:
  {
   Connection: keep-alive
 Access-Control-Allow-Origin: *
 Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested- 
With
 Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS
  Cache-Control: no-cache, private
 Date: Sat, 28 Dec 2019 00:00:04 GMT
 Set-Cookie:laravel_session=eyJpdiI6IlI2MUdzOFJmS0RcL1k1VmJCeTc4bk1nPT0iLCJ2YWx1ZSI6IlZXNW11MGw2bXk0ajFEaTM2VnhmbUZjQnFzdnRDRHV5ejJMaDRqTVJYQm1yclNyUUkweDNRMUhpZDZwblpES1MiLCJtYWMiOiI0NmFiODA4YzEyNTkxZDllNDViNGUwOGIzYjY2ZWYxZGQwNzI1NmZmYzYxYTBkZGU0M2NmMDBlYzIzN2E3OTFjIn0%3D; expires=Sat, 28-Dec-2019 02:00:04 GMT; Max-Age=7200; path=/; httponly
Server: Apache
Content-Length: 21
Content-Type: text/html; charset=UTF-8
}}
4

2 回答 2

0

您很可能有一个在 Postman 中设置的 C# 中未设置的标头、cookie 等。有几种方法可以确定 Postman 中设置了哪些属性。我在这里回答了一个类似的问题。不需要 Fiddler 或其他一些单独的工具。

于 2019-12-28T02:48:28.230 回答
0

必须添加Authorization header,这个是postman添加计算的,可以copy/post。如果您使用的是基本身份验证,请执行以下操作。

client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", "从邮递员那里复制的值");

于 2020-12-03T14:52:02.870 回答