【问题标题】:the url can't be found in angularjs在angularjs中找不到url
【发布时间】:2016-08-01 14:43:19
【问题描述】:

我是 webapi 和 angularjs 的新手。我正在尝试开发一个 angular js。我有这个控制器:

 public class ManageStudentInfoController : Controller
    {
        // GET: ManageStudentInfo
        public ActionResult Index()
        {
            return View();
        }
        public ActionResult AddNewStudent()
        {
            return PartialView("AddStudent");
        }

        public ActionResult ShowStudents()
        {
            return PartialView("ShowAllStudent");
        }

        public ActionResult EditStudent()
        {
            return PartialView("EditStudent");
        }

        public ActionResult DeleteStudent()
        {
            return PartialView("DeleteStudent");
        }
    }

还有这个 webapi 控制器:

 public class ManageStudentInfoAPIController : ApiController
    {
        private SchoolManagementEntities db = new SchoolManagementEntities();

        // GET: api/ManageStudentsInfoAPI  
        public IQueryable<Student> GetStudent()
        {
            return db.Students;
        }

        // GET: api/ManageStudentsInfoAPI/5  
        [ResponseType(typeof(Student))]
        public IHttpActionResult GetStudent(int id)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return NotFound();
            }

            return Ok(student);
        }

        // PUT: api/ManageStudentsInfoAPI/5  
        [ResponseType(typeof(void))]
        public IHttpActionResult PutStudent(int id, Student student)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            if (id != student.StudentID)
            {
                return BadRequest();
            }

            db.Entry(student).State = EntityState.Modified;

            try
            {
                db.SaveChanges();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!StudentExists(id))
                {
                    return NotFound();
                }
                else
                {
                    throw;
                }
            }

            return StatusCode(HttpStatusCode.NoContent);
        }

        // POST: api/ManageStudentsInfoAPI  
        [ResponseType(typeof(Student))]
        public IHttpActionResult PostStudent(Student student)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            db.Students.Add(student);
            db.SaveChanges();

            return CreatedAtRoute("DefaultApi", new { id = student.StudentID }, student);
        }

        // DELETE: api/ManageStudentsInfoAPI/5  
        [ResponseType(typeof(Student))]
        public IHttpActionResult DeleteStudent(int id)
        {
            Student student = db.Students.Find(id);
            if (student == null)
            {
                return NotFound();
            }

            db.Students.Remove(student);
            db.SaveChanges();

            return Ok(student);
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }

        private bool StudentExists(int id)
        {
            return db.Students.Count(e => e.StudentID == id) > 0;
        }
    }

我在 myscript 文件夹中有这个 js 文件:

模块文件:

var app = angular.module("ApplicationModule", ["ngRoute"]);

app.factory("ShareData", function () {
    return { value: 0 }
});

//Showing Routing  
app.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
    debugger;
    $routeProvider.when('/showstudents',
                        {
                            templateUrl: 'ManageStudentInfo/ShowStudents',
                            controller: 'ShowStudentsController'
                        });
    $routeProvider.when('/addstudent',
                        {
                            templateUrl: 'ManageStudentInfo/AddNewStudent',
                            controller: 'AddStudentController'
                        });
    $routeProvider.when("/editStudent",
                        {
                            templateUrl: 'ManageStudentInfo/EditStudent',
                            controller: 'EditStudentController'
                        });
    $routeProvider.when('/deleteStudent',
                        {
                            templateUrl: 'ManageStudentInfo/DeleteStudent',
                            controller: 'DeleteStudentController'
                        });
    $routeProvider.otherwise(
                        {
                            redirectTo: '/'
                        });

    $locationProvider.html5Mode(true).hashPrefix('!')
}]);

service.js 文件:

app.service("SPACRUDService", function ($http) {

    //Read all Students  
    this.getStudents = function () {

        return $http.get("/api/ManageStudentInfoAPI");
    };

    //Fundction to Read Student by Student ID  
    this.getStudent = function (id) {
        return $http.get("/api/ManageStudentInfoAPI/" + id);
    };

    //Function to create new Student  
    this.post = function (Student) {
        var request = $http({
            method: "post",
            url: "/api/ManageStudentInfoAPI",
            data: Student
        });
        return request;
    };

    //Edit Student By ID   
    this.put = function (id, Student) {
        var request = $http({
            method: "put",
            url: "/api/ManageStudentInfoAPI/" + id,
            data: Student
        });
        return request;
    };

    //Delete Student By Student ID  
    this.delete = function (id) {
        var request = $http({
            method: "delete",
            url: "/api/ManageStudentInfoAPI/" + id
        });
        return request;
    };
});

还有我的 index.html 视图:

@{
    ViewBag.Title = "SPA";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<body data-ng-app="ApplicationModule">
    <div>
        <div>
            <div>
                <table cellpadding="5" cellspacing="6" width="100%" style="background-color:whitesmoke; border:solid 4px green;">
                    <tr>
                        <td style="border: solid 1px gray; width:170px; text-align:center;"><a href="managestudentinfo/showstudents"> Show All Students </a></td>
                        <td style="border: solid 1px gray; width:170px; text-align:center;"><a href="managestudentinfo/AddNewStudent"> Add New Student </a></td>
                        <td></td>
                    </tr>
                </table>
            </div>
            <div>
                <div data-ng-view></div>
            </div>
        </div>
    </div>

</body>

@section scripts{
    <script type="text/javascript" src="@Url.Content("~/Scripts/angular.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/Scripts/angular-route.min.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/MyScripts/Module.js")"></script>
    <script src="~/MyScripts/Services.js"></script>
    <script type="text/javascript" src="@Url.Content("~/MyScripts/ShowStudentsController.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/MyScripts/AddStudentController.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/MyScripts/EditStudentController.js")"></script>
    <script type="text/javascript" src="@Url.Content("~/MyScripts/DeleteStudentController.js")"></script>
}

如果您需要,可以使用其他文件。问题是当我运行项目时,当我转到此 url 时:http://localhost:5411/showstudents 浏览器找不到该 url。

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: /showstudents

【问题讨论】:

  • 你在 iisexpress @ 5411 端口上运行你的 webapi 吗?
  • @dreamweiver 是的,它有效
  • 你是说你的问题已经解决了吗?
  • 不,我没有说,我说我的 webapi 工作正常,不是我的所有项目,因为我测试了我的 webapi 控制器并且它工作正常
  • 嗯,那到底是什么问题?显然这是行不通的,因为这不是您的 webapi,http://localhost:5411/showstudents url。你能解释一下你的问题到底是什么

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


【解决方案1】:

URL:http://localhost:5411/showstudents 是在 Angular 中定义的,而不是在 mvc 中定义的,因此是 404

解决方案:

将 routeconfig.cs 文件中的 RegisterRoute 更新为

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 },
            constraints: new { controller = "Home|Api|Account|App|token" } // this is basically a regular expression
        );
        routes.MapRoute(
            "Angular",
            "{*url}",
            defaults: new { controller = "Home", action = "Index" }
        );
    }

这会将所有 404 路由从 mvc 重定向到角度路由

查看更多详情: http://www.mithunvp.com/using-angular-2-asp-net-mvc-5-visual-studio/

【讨论】:

    【解决方案2】:

    首先,您不能将路由'ManageStudentInfo/ShowStudents' 用作templateurl。它应该是一个 HTML 文件,当您访问状态时将加载该文件,并且您的名称中有一个 ActionResult 方法

     public ActionResult ShowStudents()
            {
                return PartialView("ShowAllStudent");
            }
    

    和角度路线状态为

    $routeProvider.when('/showstudents',
        {
           templateUrl: 'ManageStudentInfo/ShowStudents',
           controller: 'ShowStudentsController'
        });
    

    两个名称相同,因此当您请求此url 时,angular 正在尝试加载其状态,而 asp.net 正在尝试加载其 Actionresult。两者都是冲突的,所以给他们不同的名字,你也可以试试这样的 url 与控制器名称

    http://localhost:5411/ManageStudentInfo/showstudents
    

    希望对你有帮助

    【讨论】:

      【解决方案3】:

      虽然不是直接回答您的问题,但这里有一个工具/技术可以让您解决此类问题

      Swashbuckle 是一种允许您访问 WebApi 的 Swagger 规范的工具。

      这意味着,您将能够看到应该如何使用 HTTP 调用您的 WebApi

      如何安装 Swashbuckle

      以 nuget 形式提供:Install-Package Swashbuckle 文档和来源:github.com/domaindrivendev/Swashbuckle

      它允许什么

      它将显示您的所有路线。另外,它提供了一个漂亮而干净的文档。 您甚至可以从那里调用您的 api,并查看组装好的 url。

      简单到然后去localhost:PORT_HERE/swagger

      想先试试

      见:http://petstore.swagger.io/#!/pet/getPetById

      【讨论】:

        【解决方案4】:

        您正在尝试访问一个不存在的 URI:localhost:5411/showstudents 在您的服务器上不存在。

        您的 /showstudents 路由映射仅在 AngularJS 中有效,使用您的实际配置的正确 URI 是:localhost:5411/#/showstudents(注意哈希)。那是因为路由是由 JavaScript 中的 AngularJS 处理的,而不是由服务器处理的。

        您可以按照以下问题中的说明从 URI 中的哈希中删除依赖项:AngularJS routing without the hash '#',但请注意,这只有在您点击已生成的 AngularJS 视图中的链接时才有效。

        在继续之前,我建议您阅读有关how routing works inside AngularJS 的更多信息。

        【讨论】:

          【解决方案5】:

          不要忘记网址中的“api”:

          http://localhost:5411/api/showstudents

          【讨论】:

          • 我不这么认为,因为我在我的模块和服务中处理它,对吗?
          猜你喜欢
          • 2017-07-08
          • 2014-10-04
          • 2013-04-22
          • 1970-01-01
          • 2013-07-13
          • 1970-01-01
          • 1970-01-01
          • 2017-05-22
          • 1970-01-01
          相关资源
          最近更新 更多