简体   繁体   English

C#HttpClient PostAsync无法与Django Rest框架一起使用

[英]C# HttpClient PostAsync won't work with django rest framework

in Django (DRF) 在Django(DRF)中

in test.views.py 在test.views.py中

class TestAPIView(APIView):

    permission_classes = (AllowAny,)
    def post(self, request, format=None):
        print(request.data)
        return Response(request.data)

in test.urls.py 在test.urls.py中

from django.conf.urls import url
from .views import TestAPIView

urlpatterns = [
    url(r'^test/$', view=TestAPIView.as_view()),
]

as you can see, my test url should return the post data. 如您所见,我的测试网址应返回发布数据。 and which does works well in browsable api and Unity WWW(something like httpclient which unity provides). 并且在可浏览的api和Unity WWW(类似于由unity提供的httpclient)中效果很好。

but it wont work with HttpClient PostAsync(or SendAsync either) 但它不能与HttpClient PostAsync(或SendAsync)一起使用

this is my C# code 这是我的C#代码

in Xamarin / C# 在Xamarin / C#中

    Post newPost = new Post { Title = "asdfasfa", Content = "asdfasffasf" };

    var content = JsonConvert.SerializeObject(newPost);

    Debug.WriteLine(content);

    var response = await _client.PostAsync("http://127.0.0.1:8000/test/", new StringContent(content));

    var responseString = await response.Content.ReadAsStringAsync();

    Debug.WriteLine(responseString);

and the results from the console.... 以及来自控制台的结果。

in C# Console 在C#控制台中

the commented string was written by me. 评论的字符串是我写的。 not from the console 不是从控制台

{"Id":0,"Title":"asdfasfa","Content":"asdfasffasf"} // <- this is the sent data.
Thread started:  #6
Thread started:  #16
Thread started:  #17
{} // <- and the received data

and... 和...

in Django(DRF) Console 在Django(DRF)控制台中

[26/Feb/2017 13:37:34] "POST /test/ HTTP/1.1" 200 2
<QueryDict: {}>

where did my post datas gone??? 我的帖子数据哪里去了??? django received <QueryDict: {}> django收到了<QueryDict: {}>

and this only happens for httpclient. 这仅适用于httpclient。 and maybe only with django. 也许只有django。 i tested it with => https://jsonplaceholder.typicode.com/posts and the post creation just worked fine. 我用=> https://jsonplaceholder.typicode.com/posts进行了测试,并且帖子创建工作正常。

It could be a Django problem, could be a C# problem, I don't know... help please! 可能是Django问题,也可能是C#问题,我不知道...请帮助!

ps?. PS? HttpWebRequest just works fine too. HttpWebRequest也可以正常工作。

我根本不了解C#,但根据其他帖子( 对Webapi的httpclient调用以发布不起作用的数据HttpClient没有发布表单数据 ),您可能需要在StringContent设置更多信息:

StringContent(content, Encoding.UTF8, "application/json")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM