如何通过C#将JSON成功发布到通过JSON内容进行身份验证的Python Flask路由?

如何通过C#将JSON成功发布到通过JSON内容进行身份验证的Python Flask路由?,c#,python,flask,C#,Python,Flask,我在一个Flask项目中编写了一个基本的API,允许通过JSON字符串发布数据。JSON需要两个属性:username和apikey,这两个属性通过以下装饰程序进行验证: def apikey_required(f): @wraps(f) def decorated_function(*args, **kwargs): if not request.json: abort(404) json_data = request.j

我在一个Flask项目中编写了一个基本的API,允许通过JSON字符串发布数据。JSON需要两个属性:
username
apikey
,这两个属性通过以下装饰程序进行验证:

def apikey_required(f):
    @wraps(f)
    def decorated_function(*args, **kwargs):
        if not request.json:
            abort(404)
        json_data = request.json
        if not 'username' in json_data or not 'apikey' in json_data:
            abort(404)
        user = User.query.filter(User.username == json_data['username']).first()
        if not user or user.status != "superuser":
            abort(404)
        if not user.apikey or user.apikey != json_data['apikey']:
            return jsonify({'status': 'error', 'message': 'unrecognized API key'})
        return f(*args, **kwargs)
    return decorated_function
我已经使用这个decorator编写了路由,它们在Python应用程序中工作得很好:下面是API路由的基本结构:

@mod.route('/invadd', methods=['GET', 'POST'])
@apikey_required
def invadd():
    json = request.json
#lots of application-specific logic that passes unit tests
我的烧瓶单元测试工作正常:

good_post_response = self.app.post(
   'api/invadd', data=json.dumps(test_json), 
   content_type='application/json') # assertions which verify the reponse pass
response = urllib2.urlopen(req, json.dumps(post_json)) #req is an api route URL
response_json = json.loads(response.read())
我编写的Python应用程序运行良好:

good_post_response = self.app.post(
   'api/invadd', data=json.dumps(test_json), 
   content_type='application/json') # assertions which verify the reponse pass
response = urllib2.urlopen(req, json.dumps(post_json)) #req is an api route URL
response_json = json.loads(response.read())
但在我的C#应用程序中,我得到了一个
SocketException:无法建立连接,因为目标机器主动拒绝了它。
当我尝试将JSON发布到这些相同的路由时。以下是相关的代码片段:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create();
request.ContentType = "application/json";
request.Method = "POST";
request.ContentLength = postJSON.Length;
using (StreamWriter sw = new StreamWriter(request.GetRequestStream()))  <--- FAILURE POINT
{
    sw.Write(postJSON.ToString());
    sw.Flush();
    sw.Close();
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
using (StreamReader sr = new StreamReader(response.GetResponseStream()))
{
    string result = sr.ReadToEnd();
    AddFeedback(result);
}

我很清楚,失败发生在应用程序尝试启动到路由的连接时,因为它从未到达实际尝试发布JSON数据的位置。但我不知道该怎么解决这个问题。我需要更改我的Flask路由吗?

这种异常表明套接字级别存在错误-这是在您访问JSON甚至HTTP之前发生的

确保连接到正确的机器和端口

现在还不清楚您在C代码中的哪个位置输入了这些数据-您可能应该使用
WebRequest.Create(“您的URL”)

您还可以尝试使用浏览器进行连接,并查看它是否正常工作


如果所有这些细节都正确,您可以使用wireshark检查到底是什么导致连接失败

非常好的建议。我一定会查看WireShark。您可以检查
request.json
中是否存在
username或apikey
。不应该是
username和apikey
?@MauroBaraldi否,
username
apikey
都必须在JSON请求中。如果其中一个丢失,应用程序将返回404(通过模糊实现安全性),您可以检查
resquest.json
中是否存在用户名和apikey。其他所有内容都是
False