简体   繁体   English

带有WCF服务的Angular JS中的405(不允许使用方法)

[英]405 (Method Not Allowed) in Angular JS With WCF Service

Currently I am working on WCF project. 目前,我正在从事WCF项目。 I am consuming my wcf project into Angular JS Application but when I run the application it does not provide any error. 我正在将wcf项目消耗到Angular JS应用程序中,但是当我运行该应用程序时,它没有提供任何错误。 There are errors when I launch developer tools in Google Chrome and I cannot insert, update and delete etc. It's showing following errors...... Anyone help me to correct this errors I would be grateful. 当我在Google Chrome中启动开发人员工具时出现错误,并且无法插入,更新和删除等。它显示以下错误……任何人都可以帮助我纠正此错误,我将不胜感激。

?o=3&g=EC0825C4-90A4-2692-D257-CD2C2B565912&s=1A2C77E8-0498-4A11-B8B8-D740DBEC71C4&z=1403834305:2 Uncaught SyntaxError: Unexpected token <
2angular.js:12701 OPTIONS http://localhost:50028/StudentService.svc/AddNewStudent 405 (Method Not Allowed)

Index:1 XMLHttpRequest cannot load http://localhost:50028/StudentService.svc/AddNewStudent. Response for preflight has invalid HTTP status code 405
Modules.js:52 Some error Occured[object Object]
Index:1 GET http://localhost:50028/StudentService.svc/GetAllStudent/ 400 (Bad Request)
angular.js:14642 ReferenceError: $log is not defined
    at Modules.js:18
    at angular.js:17000
    at m.$digest (angular.js:18182)
    at m.$apply (angular.js:18480)
    at l (angular.js:12501)
    at XMLHttpRequest.s.onload (angular.js:12655) "Possibly unhandled rejection: {}"

Her is code in Angular JS ... 她是Angular JS中的代码...

/// <reference path="../angular.min.js" />  
var app;

(function () {
    app = angular.module("RESTClientModule", []);

    app.controller("CRUD_AngularJs_RESTController", function ($scope, CRUD_AngularJs_RESTService) {

        $scope.OperType = 1;
        //1 Mean New Entry  

        GetAllRecords();
        //To Get All Records  
        function GetAllRecords() {
            var promiseGet = CRUD_AngularJs_RESTService.getAllStudent();
            promiseGet.then(function (pl) { $scope.Students = pl.data },
                function (errorPl) {
                    $log.error('Some Error in Getting Records.', errorPl);
                });
        }

        //To Clear all input controls.  
        function ClearModels() {
            $scope.OperType = 1;
            $scope.StudentID = "";
            $scope.Name = "";
            $scope.Email = "";
            $scope.Class = "";
            $scope.EnrollYear = "";
            $scope.City = "";
            $scope.Country = "";
        }

        //To Create new record and Edit an existing Record.  
        $scope.save = function () {
            var Student = {
                Name: $scope.Name,
                Email: $scope.Email,
                Class: $scope.Class,
                EnrollYear: $scope.EnrollYear,
                City: $scope.City,
                Country: $scope.Country
            };
            if ($scope.OperType === 1) {
                var promisePost = CRUD_AngularJs_RESTService.post(Student);
                promisePost.then(function (pl) {
                    $scope.StudentID = pl.data.StudentID;
                    GetAllRecords();

                    ClearModels();
                }, function (err) {
                    console.log("Some error Occured" + err);
                });
            } else {
                //Edit the record      
                debugger;
                Student.StudentID = $scope.StudentID;
                var promisePut = CRUD_AngularJs_RESTService.put($scope.StudentID, Student);
                promisePut.then(function (pl) {
                    $scope.Message = "Student Updated Successfuly";
                    GetAllRecords();
                    ClearModels();
                }, function (err) {
                    console.log("Some Error Occured." + err);
                });
            }
        };

        //To Get Student Detail on the Base of Student ID  
        $scope.get = function (Student) {
            var promiseGetSingle = CRUD_AngularJs_RESTService.get(Student.StudentID);
            promiseGetSingle.then(function (pl) {
                var res = pl.data;
                $scope.StudentID = res.StudentID;
                $scope.Name = res.Name;
                $scope.Email = res.Email;
                $scope.Class = res.Class;
                $scope.EnrollYear = res.EnrollYear;
                $scope.City = res.City;
                $scope.Country = res.Country;
                $scope.OperType = 0;
            },
                function (errorPl) {
                    console.log('Some Error in Getting Details', errorPl);
                });
        }

        //To Delete Record  
        $scope.delete = function (Student) {
            var promiseDelete = CRUD_AngularJs_RESTService.delete(Student.StudentID);
            promiseDelete.then(function (pl) {
                $scope.Message = "Student Deleted Successfuly";
                GetAllRecords();
                ClearModels();
            }, function (err) {
                console.log("Some Error Occured." + err);
            });
        }
    });

    app.service("CRUD_AngularJs_RESTService", function ($http) {
        //Create new record  
        this.post = function (Student) {
            var request = $http({
                method: "post",
                url: "http://localhost:50028/StudentService.svc/AddNewStudent",
                data: Student
            });
            return request;
        }

        //Update the Record  
        this.put = function (StudentID, Student) {
            debugger;
            var request = $http({
                method: "put",
                url: "http://localhost:50028/StudentService.svc/UpdateStudent",
                data: Student
            });
            return request;
        }

        this.getAllStudent = function () {
            return $http.get("http://localhost:50028/StudentService.svc/GetAllStudent");
        };

        //Get Single Records  
        this.get = function (StudentID) {
            return $http.get("http://localhost:50028/StudentService.svc/GetStudentDetails/" + StudentID);
        }

        //Delete the Record  
        this.delete = function (StudentID) {
            var request = $http({
                method: "delete",
                url: "http://localhost:50028/StudentService.svc/DeleteStudent/" + StudentID
            });
            return request;
        }

    });

})();

Here is the WCF service Code ...... 这是WCF服务代码......

 [ServiceContract]
    public interface IStudentService
    {

        [OperationContract]
        [WebInvoke(Method = "GET",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/GetAllStudent/")]
        List<StudentDataContract> GetAllStudent();

        [OperationContract]
        [WebGet(RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "/GetStudentDetails/{StudentId}")]
        StudentDataContract GetStudentDetails(string StudentId);

        [OperationContract]
        [WebInvoke(Method = "POST",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
             UriTemplate = "/AddNewStudent")]
        bool AddNewStudent(StudentDataContract student);

        [OperationContract]
        [WebInvoke(Method = "PUT",
           RequestFormat = WebMessageFormat.Json,
           ResponseFormat = WebMessageFormat.Json,
           UriTemplate = "/UpdateStudent")]
        void UpdateStudent(StudentDataContract contact);

        [OperationContract]
        [WebInvoke(Method = "DELETE",
            RequestFormat = WebMessageFormat.Json,
            ResponseFormat = WebMessageFormat.Json,
            UriTemplate = "DeleteStudent/{StudentId}")]
        void DeleteStudent(string StudentId);
    }
}

Here is Implementation of method of wcf service 这是WCF服务方法的实现

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

namespace WCF_REST_Service
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "StudentService" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select StudentService.svc or StudentService.svc.cs at the Solution Explorer and start debugging.
    public class StudentService : IStudentService
    {
        StudentManagementEntities ctx;

        public StudentService()
        {
            ctx = new StudentManagementEntities();
        }

        public List<StudentDataContract> GetAllStudent()
        {
            var query = (from a in ctx.Students
                         select a).Distinct();

            List<StudentDataContract> studentList = new List<StudentDataContract>();

            query.ToList().ForEach(rec =>
            {
                studentList.Add(new StudentDataContract
                {
                    StudentID = Convert.ToString(rec.StudentID),
                    Name = rec.Name,
                    Email = rec.Email,
                    EnrollYear = rec.EnrollYear,
                    Class = rec.Class,
                    City = rec.City,
                    Country = rec.Country
                });
            });
            return studentList;
        }

        public StudentDataContract GetStudentDetails(string StudentId)
        {
            StudentDataContract student = new StudentDataContract();

            try
            {
                int Emp_ID = Convert.ToInt32(StudentId);
                var query = (from a in ctx.Students
                             where a.StudentID.Equals(Emp_ID)
                             select a).Distinct().FirstOrDefault();

                student.StudentID = Convert.ToString(query.StudentID);
                student.Name = query.Name;
                student.Email = query.Email;
                student.EnrollYear = query.EnrollYear;
                student.Class = query.Class;
                student.City = query.City;
                student.Country = query.Country;
            }
            catch (Exception ex)
            {
                throw new FaultException<string>
                        (ex.Message);
            }
            return student;
        }

        public bool AddNewStudent(StudentDataContract student)
        {
            try
            {
                Student std = ctx.Students.Create();
                std.Name = student.Name;
                std.Email = student.Email;
                std.Class = student.Class;
                std.EnrollYear = student.EnrollYear;
                std.City = student.City;
                std.Country = student.Country;

                ctx.Students.Add(std);
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new FaultException<string>
                        (ex.Message);
            }
            return true;
        }

        public void UpdateStudent(StudentDataContract student)
        {
            try
            {
                int Stud_Id = Convert.ToInt32(student.StudentID);
                Student std = ctx.Students.Where(rec => rec.StudentID == Stud_Id).FirstOrDefault();
                std.Name = student.Name;
                std.Email = student.Email;
                std.Class = student.Class;
                std.EnrollYear = student.EnrollYear;
                std.City = student.City;
                std.Country = student.Country;

                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new FaultException<string>
                        (ex.Message);
            }
        }

        public void DeleteStudent(string StudentId)
        {
            try
            {
                int Stud_Id = Convert.ToInt32(StudentId);
                Student std = ctx.Students.Where(rec => rec.StudentID == Stud_Id).FirstOrDefault();
                ctx.Students.Remove(std);
                ctx.SaveChanges();
            }
            catch (Exception ex)
            {
                throw new FaultException<string>
                        (ex.Message);
            }
        }
    }
}

Here is HTML CODE ... 这是HTML代码...

@{
    Layout = null;
}

<!DOCTYPE html>

<html data-ng-app="RESTClientModule">
<head title="ASAS">
    <title></title>
    <script src="~/Scripts/angular.min.js"></script>
    <script src="~/Scripts/MyScripts/Modules.js"></script>
</head>
<body>
    <table id="tblContainer" data-ng-controller="CRUD_AngularJs_RESTController">
        <tr>
            <td>
                <table style="border: solid 2px Green; padding: 5px;">
                    <tr style="height: 30px; background-color: skyblue; color: maroon;">
                        <th></th>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Email</th>
                        <th>Class</th>
                        <th>Year</th>
                        <th>City</th>
                        <th>Country</th>
                        <th></th>
                        <th></th>
                    </tr>
                    <tbody data-ng-repeat="stud in Students">
                        <tr>
                            <td></td>
                            <td><span>{{stud.StudentID}}</span></td>
                            <td><span>{{stud.Name}}</span></td>
                            <td><span>{{stud.Email}}</span></td>
                            <td><span>{{stud.Class}}</span></td>
                            <td><span>{{stud.EnrollYear}}</span></td>
                            <td><span>{{stud.City}}</span></td>
                            <td><span>{{stud.Country}}</span></td>
                            <td>
                                <input type="button" id="Edit" value="Edit" data-ng-click="get(stud)" />
                            </td>
                            <td>
                                <input type="button" id="Delete" value="Delete" data-ng-click="delete(stud)" />
                            </td>
                        </tr>
                    </tbody>
                </table>
            </td>
        </tr>
        <tr>
            <td>
                <div style="color: red;">{{Message}}</div>
                <table style="border: solid 4px Red; padding: 2px;">
                    <tr>
                        <td></td>
                        <td>
                            <span>Student ID</span>
                        </td>
                        <td>
                            <input type="text" id="StudentID" readonly="readonly" data-ng-model="StudentID" />
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <span>Student Name</span>
                        </td>
                        <td>
                            <input type="text" id="sName" required data-ng-model="Name" />
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <span>Email</span>
                        </td>
                        <td>
                            <input type="text" id="sEmail" required data-ng-model="Email" />
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <span>Class</span>
                        </td>
                        <td>
                            <input type="text" id="sClass" required data-ng-model="Class" />
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <span>Enrollement Year</span>
                        </td>
                        <td>
                            <input type="text" id="sEnrollYear" required data-ng-model="EnrollYear" />
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <span>City</span>
                        </td>
                        <td>
                            <input type="text" id="sCity" required data-ng-model="City" />
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td>
                            <span>Country</span>
                        </td>
                        <td>
                            <input type="text" id="sCountry" required data-ng-model="Country" />
                        </td>
                    </tr>
                    <tr>
                        <td></td>
                        <td></td>
                        <td>
                            <input type="button" id="save" value="Save" data-ng-click="save()" />
                            <input type="button" id="Clear" value="Clear" data-ng-click="clear()" />
                        </td>
                    </tr>
                </table>
            </td>
        </tr>
    </table>
</body>
</html>

Here is screen shot when I run the application.. 这是我运行应用程序时的屏幕截图。 点击这里查看结果

First, you need to use * in [ServiceContract] . 首先,您需要在[ServiceContract]使用* like this: 像这样:

[WebInvoke(Method = "*"

That way, you allow your method to receive OPTIONS requests. 这样,您就可以让您的方法接收OPTIONS请求。

Then you should add this to your web.config : 然后,应将其添加到web.config

<httpProtocol>
  <customHeaders>
    <add name="Access-Control-Allow-Origin" value="*"/>
    <add name="Access-Control-Allow-Headers" value="X-Requested-With,Content-Type, Accept" />
  </customHeaders>
</httpProtocol>

Do not forgot to handle OPTIONS requests. 不要忘记处理OPTIONS请求。 Something like this will solve it: 这样的事情将解决它:

public List<StudentDataContract> GetAllStudent()
        {
          if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            return null;            
          var query = (from a in ctx.Students
                         select a).Distinct();

            List<StudentDataContract> studentList = new List<StudentDataContract>();

            query.ToList().ForEach(rec =>
            {
                studentList.Add(new StudentDataContract
                {
                    StudentID = Convert.ToString(rec.StudentID),
                    Name = rec.Name,
                    Email = rec.Email,
                    EnrollYear = rec.EnrollYear,
                    Class = rec.Class,
                    City = rec.City,
                    Country = rec.Country
                });
            });
            return studentList;
        }

That's it. 而已。 Good luck. 祝好运。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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