我在.NET中创建一个应用程序,将作为我已经部署Django应用程序的第二UI。对于某些操作需要用户验证自己的身份(如Django的用户)。我用超简单的方法来做到这一点(不加密为简单起见凭证): -

步骤1.我创建的通过两个HTTP GET参数接受用户名和密码Django视图和传递它们到django.contrib.auth.authenticate()作为关键字参数。请参见下面的代码:     

    def authentication_api(request, raw_1, raw_2):
        user = authenticate(username=raw_1, password=raw_2)
        if user is not None:
            if user.is_active:
                return HttpResponse("correct", mimetype="text/plain")
            else:
                return HttpResponse("disabled", mimetype="text/plain")
        else:
            return HttpResponse("incorrect", mimetype="text/plain")

步骤2.我称这在.NET中使用以下代码。在以下的“strAuthURL” representes映射到上述的django视图一个简单的django URL:     

    Dim request As HttpWebRequest = CType(WebRequest.Create(strAuthURL), HttpWebRequest)
    Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
    Dim reader As StreamReader = New StreamReader(response.GetResponseStream())
    Dim result As String = reader.ReadToEnd()
    HttpWResp.Close()

这完美的作品,但它只不过是一个证明的概念了。

现在我想,所以我做了以下通过HTTP POST做到这一点: -

我使用POST数据创建Django视图的操作的方式认证     

    def post_authentication_api(request):
        if request.method == 'POST':
            user = authenticate(username=request.POST['username'], password=request.POST['password'])
            if user is not None:
                if user.is_active:
                    return HttpResponse("correct", mimetype="text/plain")
                else:
                    return HttpResponse("disabled", mimetype="text/plain")
            else:
                return HttpResponse("incorrect", mimetype="text/plain")

I have tested this using restclient and this view works as expected. However I can't get it to work from the .NET code below:     

    Dim request As HttpWebRequest = CType(WebRequest.Create(strAuthURL), HttpWebRequest)
    request.ContentType = "application/x-www-form-urlencoded"
    request.Method = "POST"
    Dim encoding As New UnicodeEncoding
    Dim postData As String = "username=" & m_username & "&password=" & m_password
    Dim postBytes As Byte() = encoding.GetBytes(postData)
    request.ContentLength = postBytes.Length
    Try
        Dim postStream As Stream = request.GetRequestStream()
        postStream.Write(postBytes, 0, postBytes.Length)
        postStream.Close()
        Dim response As HttpWebResponse = CType(request.GetResponse(), HttpWebResponse)
        Dim responseStream As New StreamReader(response.GetResponseStream(), UnicodeEncoding.Unicode)
        result = responseStream.ReadToEnd()
        response.Close()
    Catch ex As Exception
        MessageBox.Show(ex.ToString)
    End Try

服务器给我一个500内部服务器错误。我的猜测是,POST请求没有正确设置在.NET。所以基本上,我需要了解如何调用从.net发送POST数据Django的看法提供一些指导。

谢谢, CM

有帮助吗?

解决方案

看起来确定给我。我建议使用Wireshark来看看你的RESTClient实现在页眉和发送,看看您的应用程序在发送报头是什么。

scroll top