locked
The requested resource does not support http method 'GET'. RRS feed

  • Question

  • User-1548796982 posted

    hi.

    Controller:

    namespace MyApplication.Controllers
    {
        public class TaskApiController : ApiController
        {
    
            [HttpPost]
            public IHttpActionResult Create(string UserName, string Password, string DoingDateTime, int ReferenceFrom, int ReferenceTo, string MaturityDateTime = "", int? PersonCompany_AffiliationID = null, int? SubjectID = null, string Description = "", int? ImportanceDegreeID = null, int? StatusID = null, int CompletionPercentage = 0, int? DossierID = null)
            {
                ...
                return Ok();
            }
        }
    }

    WebApiConfig.cs:

    using System.Web.Http;
    
    namespace MyApplication
    {
    	public static class WebApiConfig
    	{
    		public static void Register(HttpConfiguration config)
    		{
    			config.Routes.MapHttpRoute(
    				name: "DefaultApi",
    				routeTemplate: "api/{controller}/{action}/{username}/{password}/{id}",
    				defaults: new { id = RouteParameter.Optional }
    			);
    
    
    
                // WebAPI when dealing with JSON & JavaScript!
                // Setup json serialization to serialize classes to camel (std. Json format)
                var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
                formatter.SerializerSettings.ContractResolver =
                    new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
            }
    	}
    }
    

    and i am testing it using the following URL :

    http://localhost:3641/api/TaskApi/Create/admin/123?Description=%27hkjk%27&DoingDateTime=%271397/02/05%27&CompletionPercentage=0&ReferenceFrom=2&ReferenceTo=2

    but i get the following error on the browser:

    <Error>
    <Message>
    The requested resource does not support http method 'GET'.
    </Message>
    </Error>

    why?

    Friday, March 1, 2019 9:21 AM

All replies

  • User753101303 posted

    Hi,

    See https://www.w3schools.com/tags/ref_httpmethods.asp

    By convention GET is to read data from a web server, POST is to send data to a web server.

    [HttpPost] is to tell you'll only accept POST so you can't use GET (which is what is used when you type a url in your browser address bar). You want to call this from JavaScript. Just write an actual call based for example on the JavaScript part at https://www.c-sharpcorner.com/article/how-to-post-data-to-webapi-using-jquery/

    Friday, March 1, 2019 9:32 AM
  • User-1548796982 posted

    my ajax code:

    $.ajax({  
            url: 'localhost:3641/api/TaskApi/Create',  
    	type: 'post',
            dataType: "json",  
            data: {
                UserName: 'admin',
                Password: '123',
                Description: 'test',
                DoingDateTime: '1397/12/10',
                ReferenceFrom: 2,
                ReferenceTo: 2
            },
    		success: function (d) {
    			alert('success');
    		},
    		error: function(jqXHR,error, errorThrown) {
                        alert(jqXHR.responseText); 
    		}
            });

    it returns alert with message: "undefined" and Does not go to TaskApi action

    Friday, March 1, 2019 5:07 PM
  • User475983607 posted

    Your post is too confusing to follow at this point.   It started off with an HTTP GET error.  I imagine you made a few changes and now you are seeing a different issue. 

    There is no indication that you fixed the route.  Did you put the route back to the default?

    Anyway, try the code below to fix the new "undefined" error so you can see the actual error.

    error: function(jqXHR,error, errorThrown) {
    		alert(errorThrown); 
    }

    Friday, March 1, 2019 6:34 PM
  • User-1548796982 posted

    Your post is too confusing to follow at this point.   It started off with an HTTP GET error.  I imagine you made a few changes and now you are seeing a different issue. 

    There is no indication that you fixed the route.  Did you put the route back to the default?

    Anyway, try the code below to fix the new "undefined" error so you can see the actual error.

    error: function(jqXHR,error, errorThrown) {
    		alert(errorThrown); 
    }

    errorThrown returns empty

    Friday, March 1, 2019 6:41 PM
  • User-1548796982 posted

    There is no indication that you fixed the route. Did you put the route back to the default?

    webApiConfig.cs:

    using System.Web.Http;
    
    namespace MyApplication
    {
    	public static class WebApiConfig
    	{
    		public static void Register(HttpConfiguration config)
    		{
    			config.Routes.MapHttpRoute(
    				name: "DefaultApi",
    				routeTemplate: "api/{controller}/{action}/{username}/{password}/{id}",
    				defaults: new { id = RouteParameter.Optional }
    			);
    
    
    
                // WebAPI when dealing with JSON & JavaScript!
                // Setup json serialization to serialize classes to camel (std. Json format)
                var formatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
                formatter.SerializerSettings.ContractResolver =
                    new Newtonsoft.Json.Serialization.CamelCasePropertyNamesContractResolver();
            }
    	}
    }

    and my controller:

    namespace MyApplication.Controllers
    {
        public class TaskApiController : ApiController
        {
    
            [HttpPost]
            public IHttpActionResult Create(string UserName, string Password, string DoingDateTime, int ReferenceFrom, int ReferenceTo, string MaturityDateTime = "", int? PersonCompany_AffiliationID = null, int? SubjectID = null, string Description = "", int? ImportanceDegreeID = null, int? StatusID = null, int CompletionPercentage = 0, int? DossierID = null)
            {
                ...
                return Ok();
            }
        }
    }

    Friday, March 1, 2019 6:45 PM
  • User475983607 posted

    The AJAX URL...

    url: 'localhost:3641/api/TaskApi/Create', 

    ...does not match the route pattern.  

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

    Secondly the route pattern has a a rather large security vulnerability.  

    Set the route to the default as suggested above.

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

    Then try again.  If the Web API controller is in a different project than the AJAX script, then you needs CORS as well.

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/security/enabling-cross-origin-requests-in-web-api

    I recommend browsing the Web API docs to make sure you understand the fundamentals.

    https://docs.microsoft.com/en-us/aspnet/web-api/overview/

    Friday, March 1, 2019 7:58 PM
  • User-1548796982 posted

    ...

    Thank you for the points you mentioned

    I gave the following changes:

    WebApiConfig.cs:

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

    add below code to web.config:

    <system.webServer>
    <httpProtocol>
          <customHeaders>
            <add name="Access-Control-Allow-Origin" value="*" />
            <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept,Authorization" />
            <add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
          </customHeaders>
        </httpProtocol>
    </system.webServer>
    

    Controller:

    namespace MyApplication.Controllers
    {
        public class TaskApiController : ApiController
        {
    
            [HttpPost]
            public IHttpActionResult Create(string UserName, string Password, string DoingDateTime, int ReferenceFrom, int ReferenceTo, string MaturityDateTime = "", int? PersonCompany_AffiliationID = null, int? SubjectID = null, string Description = "", int? ImportanceDegreeID = null, int? StatusID = null, int CompletionPercentage = 0, int? DossierID = null)
            {
                ...
                return Ok();
            }
        }
    }

    and ajax:

    $.ajax({
                            url: 'localhost:3641/api/TaskApi',
                            contentType: 'application/x-www-form-urlencoded',
                            dataType: 'json',
                            data: {
                                UserName: 'admin',
                                Password: '123',
                                Description: 'test',
                                DoingDateTime: '1397/12/10',
                                ReferenceFrom: 2,
                                ReferenceTo: 2
                            },
                            type: 'Post',
                            success: function (data) {
                                alert('success');
                            }
                    , error: function (response) {
                                alert(response.responseText);
                            }
                });

    But still  response.responseText returns "undefined"

    Saturday, March 2, 2019 5:43 AM
  • User475983607 posted

    But still  response.responseText returns "undefined"

    First learn how to use the browser's dev tools.  Press F12 to open dev tools in your browser and open the Console View.

    Change the error handlers to this

    error: function (response) {
    	console.log(response);
    }

    Then send the AJAX request.

    Also use the Network View to see any error messages in the response.

    Is this an ASP,NET Core application?

    Saturday, March 2, 2019 3:28 PM
  • User36583972 posted

    Hi tadbirgaran,

    $.ajax({
                            url: 'localhost:3641/api/TaskApi',
                            contentType: 'application/x-www-form-urlencoded',
                            dataType: 'json',
                            data: {
                                UserName: 'admin',
                                Password: '123',
                                Description: 'test',
                                DoingDateTime: '1397/12/10',
                                ReferenceFrom: 2,
                                ReferenceTo: 2
                            },
                            type: 'Post',
                            success: function (data) {
                                alert('success');
                            }
                    , error: function (response) {
                                alert(response.responseText);
                            }
                });

    But still  response.responseText returns "undefined"

    When you use the ajax call with the JSON data, I suggest you change the API method like below.

             [HttpPost]
            public IHttpActionResult Create([FromBody]YourObject yourObject)
            {
                ...
                return Ok();
            }
    
    
        public class YourObject
        {
            public string  UserName { get; set; }
            public string Password{ get; set; }
            .....
        }
    

    Ajax:

                   $.ajax({
                        type: "POST",
                        url: ".....",
                        headers: { "Accept": "application/json; odata=nometadata" },
                        contentType: "application/json; charset=urf-8",
                        dataType: "json", 
                        data:  JSON.stringify(object),
                        success: function (response) {
                            alert(response);
                        }, 
                        error: function () {
                            alert("Error while invoking the Web API");
                        }
                    });

    Then, use the browser's dev tools( Press F12 to open dev tools in your browser and open the Console View) to check the message/error and modify your code.

    Best Regards

    Yong Lu

    Monday, March 4, 2019 3:19 AM