ASP.Net WebAPI 2 404错误 - 见解说不同

时间:2017-06-21 12:08:55

标签: c# asp.net asp.net-mvc asp.net-web-api

据我所知,这个问题已经被多次询问了,我已经查看了很多问题,但到目前为止,没有一个答案对我有用。

我正在使用.Net 4.5.2使用ASP.Net WebAPI 2控制器并使用Ajax发布。

我立即收到404错误,但是查看数据显示该控制器和该操作的方法有x个请求但是它立即返回404。

这是方法,如果有人能帮助我,我将不胜感激。

 [System.Web.Mvc.HttpPost()]

 public int InsertRecord(Models.Person model)
    {

        if (ModelState.IsValid)
        {
            var person = new Person
            {
                FirstName = model.FirstName,
                LastName = model.LastName,
                DateOfBirth = Convert.ToDateTime(model.DateOfBirth)
            };

            _dbContext.People.Add(person);
            _dbContext.SaveChanges();

            var id = person.P_id;

            return id;
        }
        else
        {
            throw new Exception("Invalid Data", null);
        }
    }

从我的Ajax调用如下;

 $("#btnSave").click(function () {

    $('#FirstName').valid();
    $('#LastName').valid();
    $('#DateOfBirth').valid();

    if ($('#FirstName').valid() &&
        $('#LastName').valid() &&
        $('#DateOfBirth').valid()) {
        //console.log("save clicked");
        var jsonData = {
            firstName: $('#FirstName').val(),
            lastName: $('#LastName').val(),
            dateofBirth: $('#DateOfBirth').val()
        }

        $.ajax(
            {
                type: "POST", //HTTP POST Method  
                url: "http://localhost:56658/AddPerson/InsertRecord", // Controller/View   
                data: jsonData,
                success: function (response) {
                    if (response != null && response.success) {
                        alert(response.responseText);
                    } else {
                        // DoSomethingElse()
                        alert(response.responseText);
                    }
                },
                error: function (response) {
                    alert("error!");  // 
                    console.log(response);
                }

            });
        return false;
    }



});

修改

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );

        routes.MapRoute(
            name: "AddPerson",
            url: "{controller}/{action}",
            defaults: new { controller = "AddPerson", action = "InsertRecord"}
        );
    }
}

编辑2

这是全局的asax文件内容

protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
        GlobalConfiguration.Configure(WebApiConfig.Register);
        FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
        RouteConfig.RegisterRoutes(RouteTable.Routes);
        BundleConfig.RegisterBundles(BundleTable.Bundles);

    }

编辑3

 public static class WebApiConfig
{
    public static void Register(HttpConfiguration config)
    {
        // Web API configuration and services

        // Web API routes
        config.MapHttpAttributeRoutes();

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

1 个答案:

答案 0 :(得分:0)

由于这是一个Wep API,它应该尝试遵循该设计意图

检查通常

WebApiConfic
public static class WebApiConfig {
    public static void Register(HttpConfiguration config) {
        // Attribute routing.
        config.MapHttpAttributeRoutes();

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

请注意默认路由的api前缀。这将配置如何调用Web API端点。 api前缀是为了避免与普通的MVC框架发生路由冲突。

Url看起来像api/AddPerson

接下来确保控制器正确创建并遵循建议的设计。尽量避免向控制器添加太多职责。控制器是一个UI关注点,应该尽可能精益。

public interface IAddPersonCommand {
    int? InsertRecord(Models.Person model model);
}

public class PersonController : ApiController {
    private readonly IAddPersonCommand service;
    public PersonController(IAddPersonCommand service) {
        this.service = service;
    }

    [HttpPost]
    public IHttpActionResult Post([FromBody]Models.Person model) {    
        if (ModelState.IsValid) {
            var id = service.InsertRecord(model);
            if(id !=null) {
                return Ok(id);
            }
        } 
        //If we get this far bad request
        return BadRequest();
    }
}