C# 为什么我的Post方法不被允许?
我已成功使用此方法获取REST数据:C# 为什么我的Post方法不被允许?,c#,post,json.net,asp.net-web-api-routing,http-status-code-405,C#,Post,Json.net,Asp.net Web Api Routing,Http Status Code 405,我已成功使用此方法获取REST数据: private JArray GetRESTData(string uri) { try { var webRequest = (HttpWebRequest)WebRequest.Create(uri); var webResponse = (HttpWebResponse)webRequest.GetResponse(); var reader = new StreamReader(webR
private JArray GetRESTData(string uri)
{
try
{
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
var webResponse = (HttpWebResponse)webRequest.GetResponse();
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
return JsonConvert.DeserializeObject<JArray>(s);
}
catch // This method crashes if only one json "record" is found - try this:
{
try
{
MessageBox.Show(GetScalarVal(uri));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
return null;
}
…并使用此URI调用它:
http://localhost:28642/api/Departments/PostDepartment/42/76TrombonesLedTheZeppelin
虽然我有一个对应的Post方法:
控制器
[Route("api/Departments/PostDepartment/{accountid}/{name}/{dbContext=03}")]
public void PostDepartment(string accountid, string name, string dbContext)
{
_deptsRepository.PostDepartment(accountid, name, dbContext);
}
存储库
public Department PostDepartment(string accountid, string name, string dbContext)
{
int maxId = departments.Max(d => d.Id);
// Add to the in-memory generic list:
var dept = new Department {Id = maxId + 1, AccountId = accountid, Name = name};
departments.Add(dept);
// Add to the "database":
AddRecordToMSAccess(dept.AccountId, dept.Name, dbContext);
return dept;
}
…失败,原因是“远程服务器返回错误:(405)方法不允许。”
为什么不允许呢
更新
根据我在此处找到的内容,我将其添加到Web.Config:
<validation validateIntegratedModeConfiguration="false" />
<modules runAllManagedModulesForAllRequests="true">
<remove name="WebDAVModule" />
</modules>
<handlers>
<remove name="WebDAV" />
<remove name="ExtensionlessUrlHandler-Integrated-4.0" />
<add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT"
type="System.Web.Handlers.TransferRequestHandler" resourceType="Unspecified" requireAccess="Script"
preCondition="integratedMode,runtimeVersionv4.0" />
</handlers>
我在它里面有一个断点没有到达
更新3
VirtualBlackBox的最后一条评论就是成功的关键。我刚刚将客户代码中的“这是帖子吗?”更改为:
if (uri.Contains("Post"))
{
webRequest.Method = "POST";
webRequest.ContentLength = 0; // <-- This line is all I added
}
if(uri.Contains(“Post”))
{
webRequest.Method=“POST”;
webRequest.ContentLength=0;//我不使用Asp.Net,但我猜您需要指定HttpPost
属性,如文档中所示:
[HttpPost]
[Route("api/Departments/PostDepartment/{accountid}/{name}/{dbContext=03}")]
public void PostDepartment(string accountid, string name, string dbContext)
{
_deptsRepository.PostDepartment(accountid, name, dbContext);
}
在我的电脑上工作的小样本:
TestController.cs:
using System.Web.Http;
namespace WebApplication2.Controllers
{
public class TestController : ApiController
{
[HttpPost]
[Route("api/Departments/PostDepartment/{accountid}/{name}/{dbContext=03}")]
public string PostDepartment(string accountid, string name, string dbContext)
{
return accountid + name + dbContext;
}
}
}
Test.html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
$(function () {
$.ajax("api/Departments/PostDepartment/accountid/name/dbContext", {
type: 'POST', success: function (data) {
$('#dest').text(data);
}
});
});
</script>
</head>
<body>
<div id="dest"></div>
</body>
</html>
$(函数(){
$.ajax(“api/Departments/PostDepartment/accountid/name/dbContext”{
类型:“发布”,成功:函数(数据){
$('#dest')。文本(数据);
}
});
});
在C#中调用服务的示例程序:
命名空间控制台应用程序1
{
使用制度;
使用System.IO;
Net系统;
使用Newtonsoft.Json;
班级计划
{
静态void Main()
{
Console.WriteLine(GetRestData)(@)http://localhost:52833//api/Departments/PostDepartment/42/76TrombonesLedTheZeppelin"));
Console.ReadLine();
}
私有静态动态GetRestData(字符串uri)
{
var webRequest=(HttpWebRequest)webRequest.Create(uri);
webRequest.Method=“POST”;
webRequest.ContentLength=0;
var webResponse=(HttpWebResponse)webRequest.GetResponse();
var reader=newstreamreader(webResponse.GetResponseStream());
字符串s=reader.ReadToEnd();
返回JsonConvert.DeserializeObject;
}
}
}
您可能需要在web.config
中允许它,或者在api方法allowsPOST
中添加一个属性。不过,我只有使用WCF的经验,所以不能肯定。@CodeCaster:这就是为什么我添加了查找“POST”的逻辑,因为我想使用这种新类型的方法(到目前为止,它们都是“GET”)s、 其他POST方法是否有效,或者在被请求时是否有效,例如通过jQuery?您是否尝试过“web api 405”的许多结果中的任何一个?@CodeCaster:由于CORS问题,我还没有让jQuery测试起作用()我只是尝试了一下;不过,当添加它时,它会迫使您在两种不同风格的HttpPost之间进行选择。第一种没有任何区别,第二种不会编译。有“通用”选项,然后还有一个System.Web.MVC选项。现在这两种选项都不允许我使用(System.Web.Http是另一种)。稍后:删除使用“system.web.mvc”允许我使用第一个(system.web.Http)。尽管如此,这并没有什么区别(它应该装饰控制器中的方法,对吗?)。是的,它在控制器上运行。我创建了一个小的最小示例,创建了一个新的Asp.Net项目,只检查了WebApi,并添加了一个控制器和一个小的html文件(请参阅答案中的代码)。它可以正常工作并显示“accountidnamedbContext”,正如预期的那样有趣;不过,使用jQuery路线目前对我不起作用,因为我在这方面有未解决的CORS问题(),我添加了一个对我有效的小示例程序(除了我添加了webRequest.ContentLength=0
以避免
if (uri.Contains("Post"))
{
webRequest.Method = "POST";
webRequest.ContentLength = 0; // <-- This line is all I added
}
[HttpPost]
[Route("api/Departments/PostDepartment/{accountid}/{name}/{dbContext=03}")]
public void PostDepartment(string accountid, string name, string dbContext)
{
_deptsRepository.PostDepartment(accountid, name, dbContext);
}
using System.Web.Http;
namespace WebApplication2.Controllers
{
public class TestController : ApiController
{
[HttpPost]
[Route("api/Departments/PostDepartment/{accountid}/{name}/{dbContext=03}")]
public string PostDepartment(string accountid, string name, string dbContext)
{
return accountid + name + dbContext;
}
}
}
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>
<script>
$(function () {
$.ajax("api/Departments/PostDepartment/accountid/name/dbContext", {
type: 'POST', success: function (data) {
$('#dest').text(data);
}
});
});
</script>
</head>
<body>
<div id="dest"></div>
</body>
</html>
namespace ConsoleApplication1
{
using System;
using System.IO;
using System.Net;
using Newtonsoft.Json;
class Program
{
static void Main()
{
Console.WriteLine(GetRestData(@"http://localhost:52833//api/Departments/PostDepartment/42/76TrombonesLedTheZeppelin"));
Console.ReadLine();
}
private static dynamic GetRestData(string uri)
{
var webRequest = (HttpWebRequest)WebRequest.Create(uri);
webRequest.Method = "POST";
webRequest.ContentLength = 0;
var webResponse = (HttpWebResponse)webRequest.GetResponse();
var reader = new StreamReader(webResponse.GetResponseStream());
string s = reader.ReadToEnd();
return JsonConvert.DeserializeObject<dynamic>(s);
}
}
}