简体   繁体   中英

AngularJs: $http.post always return 404 error

I am currently trying to develop a simple angular js application. I am trying to post data from client to web api. However, I am getting 404 error when I fire post request from angular app.

Below is my post request,

 $http.post('/api/LoadApi/', jsonData).then(function (result) {
                console.log(result.data);
            })
           .catch(function (error) {
           });

where jsonData is a valid json data.

My web api code is this,

public class LoadApiController : ApiController
{
    [HttpPost]
    public HttpResponseMessage LoadData(object dataToLoad)
    {
        var response = Request.CreateResponse(HttpStatusCode.Created);

        return response;
    }
}

My web api route config is this,

config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{dataToLoad}"
            );

However, when I run the code, it throws an error

Server Error in '/' Application. The resource cannot be found. Description: HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. Please review the following URL and make sure that it is spelled correctly. Requested URL: /api/LoadApi/

Can anyone point what is the problem with the above code?

It says there is some problem with url. The url generated is http://localhost:14154/api/LoadApi/ which looks correct.

The issue is with your route definition and how you are trying to send data to your controller method. I would recommend using attribute based routing. In your Web API controller do this:

[RoutePrefix("api/LoadApi")]
public class LoadApiController : ApiController
{
    [HttpPost]
    [Route("loadData")]
    public HttpResponseMessage LoadData(object dataToLoad)
    {
        var response = Request.CreateResponse(HttpStatusCode.Created);
        return response;
    }
}

Change the Application_Start() method in Global.asax.cs to this:

protected void Application_Start()
{
    GlobalConfiguration.Configure(WebApiConfig.Register);
}

Make sure WebApiConfig.cs in App_Start has a Register() method like this:

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

And finally change your $http.post call to this:

$http.post('/api/LoadApi/loadData', jsonData).then([...]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM