0

我正在尝试学习 RestApis,但遇到了一个我找不到答案的问题。

在 Python 脚本中,我在 Flask RestApi 包的帮助下运行 RestService。
所有端点都是 GET,我已经使用 PostMan 和 Web 浏览器测试和验证了每个端点。
在这两个客户端中的每一个中,我都按预期获得了 JSON 数据。

我有一个作为 RestClient 运行的 C# 控制台应用程序。
在这里,我得到状态码 308(永久重定向)。
我不明白为什么我会得到这个状态码。

Python 休息服务

from flask import Flask
from flask import jsonify

app = Flask(__name__)

@app.route('/name/')
def nameEndpoint():
    return jsonify(
    {
        'name':"Some name"
    }), 200

if __name__ == '__main__':
    app.run()

RestService 在我计算机上的 Windows 终端本地运行。
RestService 的 URL 是:http://localhost:5000/

我的 C# RestClients

var url = "http://localhost:5000/name";

public async Task TryWithRestSharp()
{
    var client = new RestSharp.RestClient(url);
    var result = await client.ExecuteAsync(new RestSharp.RestRequest());
    var json = foo.Content;
}

public async Task TryWithHttpClient()
{
    var client = new HttpClient();
    var json = await client.GetStringAsync(url);
}

两种方法都返回服务器代码 308(永久重定向)。

RestSharp 返回此信息:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>Redirecting...</title>
<h1>Redirecting...</h1>
<p>You should be redirected automatically to target URL:
<a href="http://localhost:5000/name/">http://localhost:5000/name/</a>.
If not click the link.

我发现这个关于状态码 308 的解释:

A 308 Permanent Redirect message is an HTTP response status code indicating that the 
requested resource has been permanently moved to another URI, as indicated by the 
special Location header returned within the response

我的问题:

  • 资源如何被“移动”到另一个 URI?
  • 是服务的问题还是客户端的问题?
  • 我需要做什么来解决这个问题?
4

2 回答 2

0

像这样试试

https://restsharp.dev/getting-started/getting-started.html#basic-usage

using RestSharp;
using RestSharp.Authenticators;

var client = new RestClient("your base url");

// if there is any auth
client.Authenticator = new HttpBasicAuthenticator("username", "password");

var request = new RestRequest("url prefix like url/name", DataFormat.Json);

var response = client.Get(request);
于 2021-11-22T06:04:29.817 回答
0

我发现了问题!
它在客户端。

using RestSharp;   // NOTE: Not sure if this make any difference for the problem. But it nice to have.

var url = "http://localhost:5000/name/";   // NOTE: Make sure to end the URL with a slash.

public async Task TryWithRestSharp()
{
    var client = new RestClient(url);
    var request = new RestRequest(url, DataFormat.Json);
    var result = await client.ExecuteGetAsync(new RestRequest());
    var json = result.Content;
}

我错过了 URL 中的最后一个斜杠。
这导致了问题。

于 2021-11-22T23:56:21.513 回答