ASP.NET请求的资源不支持http方法' GET'

时间:2016-07-19 00:34:38

标签: asp.net asp.net-web-api2

这应该很简单,但我不确定是什么问题。

每当我尝试访问" http://localhost:50949/api/projects"时,我都会收到以下错误

请求的资源不支持http方法' GET'

WebApiConfig

public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        config.MapHttpAttributeRoutes();

        config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );
    }
}

ApiController

private const string m_BaseUrl = "http://example.com/rest/api/2/";
    private string m_Username = Properties.Settings.Default.username;
    private string m_Password = Properties.Settings.Default.password;
    // GET: api/Projects       
    [HttpGet]
    public IEnumerable<string> Get(JiraResource resource, string argument = null, string data = null, string method = "GET")
    {
        string url = string.Format("{0}{1}/", m_BaseUrl, resource.ToString());

        HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
        request.ContentType = "application/json";
        request.Method = method;

        string base64Credentials = GetEncodedCredentials();
        request.Headers.Add("Authorization", "Basic " + base64Credentials);

        HttpWebResponse response = request.GetResponse() as HttpWebResponse;

        string result = string.Empty;
        using (StreamReader reader = new StreamReader(response.GetResponseStream()))
        {
            result = reader.ReadToEnd();
        }

        return null;
    }

    private string GetEncodedCredentials()
    {
        string mergedCredentials = string.Format("{0}:{1}", m_Username, m_Password);
        byte[] byteCredentials = UTF8Encoding.UTF8.GetBytes(mergedCredentials);
        return Convert.ToBase64String(byteCredentials);
    }

HTML / JS

<h2>Projects</h2>

<button id="projects" class="btn btn-info">List Projects</button>

@section scripts
{
    <script>
    $(document)
        .ready(function() {
            $("#projects")
                .click(function(e) {
                    var button = $(e.target);
                    $.get("/api/projects/")
                        .done(function() {                               
                            alert("Got Projects");
                        })
                        .fail(function() {
                            alert("Something failed!");
                        });
                });
        });
</script>

}

如果我通过用户界面进行操作,我会得到&#34;失败的事情&#34;

1 个答案:

答案 0 :(得分:0)

在你的方法int控制器中,你仍然需要输入route属性,即使它是空字符串:

    [HttpGet]
    [Route("")]
    public IEnumerable<string> Get(JiraResource resource, string argument = null, string data = null, string method = "GET")
    {
...
    }