API错误401未经授权的laravel C Sharp

时间:2019-03-25 20:59:07

标签: c# laravel httpclient lumen laravel-passport

我正在使用C#开发一个名为RESTApi de laravel的应用程序。通过Postman,它可以正常工作,但不是C#,而是返回错误401。

如果在Laravel控制器中可以删除以下内容,则效果很好:

if($ request-> isJson()){

标头Content-Type设置为application / json

Laravel代码

function getResult(Request $request, $id)
    {
        if ($request->isJson()) {
            // Eloquent
            $times = Result::selectRaw('THE SELECT')
                ->where('ID', $Id)
                ->get();
                $result = [];
                foreach($times as $key => $time)
                {
                 ...........
                }
                sort($result);
            return response()->json(['results'=>$result], 200);
        }

        return response()->json(['error' => 'Unauthorized'], 401, []);
    }

C#

public static async Task<dynamic> GETTimes(int eventID, int stageID)
        {
            using (var client = new HttpClient())
            {
                client.BaseAddress = new Uri(baseUrl);
                client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
                client.DefaultRequestHeaders.TryAddWithoutValidation("cache-control", "no-cache");
                client.DefaultRequestHeaders.Add("User-Agent", @"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.106 Safari/537.36");

                // Add the Authorization header with the AccessToken.
                //client.DefaultRequestHeaders.Add("Authorization", "Bearer " + accessToken);
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);

                // create the URL string.
                string url = string.Format("api/v1/events/{0}/results/{1}", eventID, stageID);

                // make the request
                HttpResponseMessage response = await client.GetAsync(url);

                // parse the response and return the data.
                string jsonString = await response.Content.ReadAsStringAsync();
                object responseData = JsonConvert.DeserializeObject(jsonString);

                return (dynamic)responseData;
            }
        }

0 个答案:

没有答案