【问题标题】:Angular - NetworkError: 404 Not Found - http://localhost:3094/api/Controller/Action/Angular - NetworkError: 404 Not Found - http://localhost:3094/api/Controller/Action/
【发布时间】:2014-12-25 10:17:22
【问题描述】:

我要将我的字符串发布到 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);
    }

【问题讨论】:

  • 您正在发帖,但服务器代码说只获取?
  • 对不起,不提这些代码了:)这只是简单的测试代码,所以我才这样调用,重点是,这个GetSelectionCount函数从UI中获取一个参数并返回一些数据到客户端。如果我将 [AcceptVerbs("GET")] 更改为 [AcceptVerbs("POST")] 或 [HttpPost] 属性,无论如何它都不起作用(((
  • 我有另一篇文章正在运行,但在这篇文章中出现错误

标签: angularjs api http-post httprequest


【解决方案1】:

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);
}

【讨论】:

  • 我在服务器端使用了一个模型作为参数,但我得到了同样的错误。然后我使用了 $http.post('localhost:3094/api/Country/GetSelectionCount' , selection) .success(function (data, status, headers, config) { deferred.resolve(data); })
  • 你能把你的模型发布到 asp.net 上吗
  • 使用系统;使用 System.Collections.Generic;使用 System.Linq;使用 System.Web;命名空间 WebApi.Demo.Models.ViewModels { public class JustModel { public string Text { get;放; } } }
  • 你需要将Text重命名为id
  • 我在答案中添加了必要的代码,以捕捉您从 angular 发布的内容
【解决方案2】:

我认为 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);
}

【讨论】:

  • 你还收到 404 消息还是别的什么?
猜你喜欢
  • 1970-01-01
  • 2018-10-27
  • 1970-01-01
  • 2014-07-29
  • 2018-09-07
  • 1970-01-01
  • 2021-12-27
  • 2015-03-20
  • 1970-01-01
相关资源
最近更新 更多