在C#中向Django REST API发出POST请求时出错

时间:2019-06-19 20:51:35

标签: c# django http post

我想向Django REST API发出POST请求。我的数据(Json字符串)位于C#应用程序中。我正在使用以下代码段:

var httpWebRequest = (HttpWebRequest)WebRequest.Create(myurl);
httpWebRequest.Method = "POST";
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
  string json = "{\"a\":\"sun\", \"b\":\"moon\"}";
  streamWriter.Write(json);
}

var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
{
  var result = streamReader.ReadToEnd();
}

不幸的是,我在“ var httpResponse =(HttpWebResponse)httpWebRequest.GetResponse();”处收到此错误。行:

System.Net.WebException: 'The remote server returned an error: (405) Method Not Allowed.' 

我还检查了Django API的日志,是Django抛出“不允许的方法”错误。

经过研究后,看来是由于我的Django REST应用程序不允许POST造成的。

我能够毫无问题地发出GET请求。为此,在我的Django REST框架应用程序中,我在views.py文件中使用了restore()函数。 我也碰巧在相同的views.py文件中有一个create()函数。我认为该功能将能够处理POST请求。

但是,由于Django应用程序立即抛出“ Method Not Allowed”(不允许方法)错误,因此我什至无法使用它。

有没有办法允许POST请求?我尝试添加装饰器

@action(detail=True, methods=['get','post']) 

在views.py文件中的create()和retrieve()函数上方,但这不起作用。我收到以下错误:

django.core.exceptions.ImproperlyConfigured: Cannot use the @action decorator on the following methods, as they are existing routes: create, retrieve

请注意,我正在使用DefaultRouter(在urls.py文件中)(以防万一)

router = routers.DefaultRouter()

我一直在对许多建议的解决方案进行在线研究,但是在我的案例中,没有一个起作用。任何帮助都非常感谢。

0 个答案:

没有答案