Angular - NetworkError:404 Not Found - http:// localhost:3094 / api / Controller / Action /

时间:2014-12-25 10:17:23

标签: angularjs api http-post httprequest

我要将我的字符串发布到api,但每次我都有这样的错误。然而,通过提琴手它工作正常

NetworkError: 404 Not Found - http://localhost:3094/api/Controller/Action/

这是我的js代码

 var deferred = $q.defer();

    $http.post('http://localhost:3094/api/Country/GetSelectionCount/' ,
        {id:selection})
        .success(function (data, status, headers, config) {
            deferred.resolve(data);
        })
        .error(function (data, status, headers, config) {
            deferred.reject(data);
        });

    return deferred.promise;

和服务器代码

 [AcceptVerbs("GET")]
    [ActionName("GetSelectionCount")]
    public IHttpActionResult GetSelectionCount(string id)
    {
        if (String.IsNullOrWhiteSpace(id))
            return NotFound();

        var result= (from m in db.Products
                     where m.ProductName.Contains(id)
                     select m).Count();

        return Ok(result);
    }

2 个答案:

答案 0 :(得分:0)

在这种情况下,404是正常的。您正在从angular发布一个具有id属性的对象,但在服务器端,您需要一个字符串属性。所以.net不能匹配行动。

您需要更改服务器端操作参数或角度发布数据

public class MyModel
{
    public string id {get;set;}
}
[AcceptVerbs("POST")]
[ActionName("GetSelectionCount")]
public IHttpActionResult GetSelectionCount([FromBody] MyModel model)
{
    if (model == null || String.IsNullOrWhiteSpace(model.id))
        return NotFound();

    var result= (from m in db.Products
                 where m.ProductName.Contains(model.id)
                 select m).Count();

    return Ok(result);
}

答案 1 :(得分:0)

我认为404更多地与路由引擎无法在控制器上找到相关的操作方法有关。您可以使用Route属性(例如

)进行确认
[AcceptVerbs("POST")]
[ActionName("GetSelectionCount")]
[Route("api/country/GetSelectionCount/")]
public IHttpActionResult GetSelectionCount(string id)
{
    if (String.IsNullOrWhiteSpace(id))
        return NotFound();

    var result= (from m in db.Products
                 where m.ProductName.Contains(id)
                 select m).Count();

    return Ok(result);
}