WCF服务方法不起作用

时间:2017-08-21 18:11:17

标签: c# linq web-services wcf

我目前正在研究wcf服务,而Service正在运行localhost。我在Wcf服务中有一些方法。当我想通过键入例如http://localhost:50028/StudentService.svc/GetAllStudent/从localhost访问该方法时,我面临一些错误 它显示以下错误。

**

Request Error
The server encountered an error processing the request. Please see the service help page for constructing valid requests to the service.

** 这是我的代码格式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);

    }

}

这是我的实施代码......

public class StudentService : IStudentService
    {
        StudentManagementEntities ctx;

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

        public List<StudentDataContract> GetAllStudent()
        {
            //if (HttpContext.Current.Request.HttpMethod == "GetAllStudent")
            //    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;
        }

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

这是web.config文件..

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <appSettings>
    <add key="aspnet:UseTaskFriendlySynchronizationContext" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5">
      <assemblies>
        <add assembly="System.Data.Entity, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
      </assemblies>
    </compilation>
    <httpRuntime targetFramework="4.5" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the values below to false before deployment -->
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false" />
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior>
          <webHttp helpEnabled="True"/>
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <protocolMapping>
      <add binding="webHttpBinding" scheme="http" />
    </protocolMapping>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.webServer>


    <modules runAllManagedModulesForAllRequests="true" />
    <!--
        To browse web app root directory during debugging, set the value below to true.
        Set to false before deployment to avoid disclosing web app folder information.
      -->

    <directoryBrowse enabled="true" />
  </system.webServer>
  <connectionStrings>
    <add name="StudentManagementEntities" connectionString="metadata=res://*/SchoolManagement.csdl|res://*/SchoolManagement.ssdl|res://*/SchoolManagement.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=KHUNDOKARNIRJOR\KHUNDOKERNIRJOR;initial catalog=Student;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

我无法访问来自localhost,它始终显示此错误

请求错误 服务器遇到处理请求的错误。请参阅服务帮助页面以构建对服务的有效请求。

这是屏幕截图Click here to see the out put

请高度赞赏任何帮助..

3 个答案:

答案 0 :(得分:0)

我在配置文件中没有看到“services”元素。请查看以下链接以配置您的服务。 Configuring Services

另一种方法是使用visual studio创建wcf服务。 Visual Studio将为您生成适当的配置文件。然后,您可以相应地替换方法,接口和配置。

我看到你正在尝试返回一个List。我不认为你可以将List作为返回参数传递。

答案 1 :(得分:0)

  

请检查&#34;上的所有方法。   http://localhost:50028/StudentService.svc&#34;请另一个建议   删除&#34; /&#34;来自uriTemplate。只需写下#34; GetAllStudent&#34;代替   &#34; / GetAllStudent /&#34;

答案 2 :(得分:0)

> <services>
>       <service name="" behaviorConfiguration="serviceBehavior">
>         <endpoint address="" binding="webHttpBinding" contract="" behaviorConfiguration="web"/>
>       </service>
>     </services>
>     <behaviors>
>       <serviceBehaviors>
>         <behavior name="serviceBehavior">
>           <serviceMetadata httpGetEnabled="true"/>
>           <serviceDebug includeExceptionDetailInFaults="false"/>
>         </behavior>
>       </serviceBehaviors>
>       <endpointBehaviors>
>         <behavior name="web">
>           <webHttp/>
>         </behavior>
>       </endpointBehaviors>
>     </behaviors>

在我看来,webconfig中缺少服务和行为标签。