问题背景:
我有一个在 Azure 中作为 WebApp 托管的基本 WebApi 项目。
问题:
我遇到的问题是,如果我访问“GET”类型以外的任何方法,那么我会在 JSON 响应中收到以下错误:
The requested resource does not support http method 'GET'
代码:
以下代码是项目当前的情况。
RouteConfig.cs
类:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Home",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
ValuesController
Controller 类:
public class ValuesController : ApiController
{
private List<CompanyData> _company;
public ValuesController()
{
_company = new List<CompanyData>
{
new CompanyData
{
CompanyName = "SmallTech.Ltd",
CompanyOwner = "John Smith",
CompanyIndustry = "Electronic Components",
EmployeeNo = "3"
}
};
}
public List<CompanyData> GetCompanyData()
{
return _company;
}
//GET api/values
public IEnumerable<string> Get()
{
return new string[] { "Test GET Method"};
}
// GET api/values/5
public string Get(int id)
{
return "value";
}
// POST api/values
public void Post(string value)
{
string test = value;
}
// PUT api/values/5
public void Put(int id, [FromBody]string value)
{
}
// DELETE api/values/5
[HttpDelete]
public void Delete(int id)
{
}
发生错误时调用上述Delete方法的示例为:
http://testwebapisite.azurewebsites.net/api/values/Delete/5
我读过其他人也有同样的问题,并且使用了 System.Net.MVC 中的 HTTP 属性。我可以确认我没有使用这个,而是使用 `System.Net.Http.HttpPostAttribute。
如果能帮助我弄清楚为什么我会收到 GET 错误消息,那就太棒了。
最佳答案
您正在尝试访问一个通过 GET 请求明确指定删除作为其动词的操作。
默认情况下,如果您粘贴网址,浏览器将执行 GET 请求,因此测试起来非常容易,但对于其他动词,您必须使用实际的 Rest/http 客户端来指定动词。如果您使用 chrome 进行开发/测试,可以使用 Postman 或 Rest Console
除了这些工具之外,您可能还需要 fiddler安装..它将帮助您跟踪所有http事件(发送/接收)您将确切地知道您从线路发送和接收的内容
如果您想使用 HttpClient
,您也可以通过代码执行此操作。
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://testwebapisite.azurewebsites.net/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = await client.DeleteAsync("api/values/5");
}
关于c# - WebApi - 请求的资源不支持http方法 'GET',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31496414/