简体   繁体   English

WCF服务方法不起作用

[英]WCF Service Method is not Working

I am currently working on wcf service and Service is running localhost.I have some methods in Wcf Service. 我目前正在使用wcf服务,并且服务正在运行localhost.Wcf服务中有一些方法。 I am facing some Errors when I want to access the method from localhost by typing for example http://localhost:50028/StudentService.svc/GetAllStudent/ its shows following errors. 我想通过输入例如http:// localhost:50028 / StudentService.svc / GetAllStudent /从本地主机访问该方法时遇到一些错误。它显示以下错误。

** **

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

** Here is my code form Wcf 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);

    }

}

Here is my code of Implementation ... 这是我的实现代码...

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

Here is the web.config file .. 这是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>

I can not access the from localhost its is always shows this error 我无法从本地主机访问它总是显示此错误

Request Error The server encountered an error processing the request. 请求错误服务器在处理请求时遇到错误。 Please see the service help page for constructing valid requests to the service. 请参阅服务帮助页面,以构造对服务的有效请求。

Here is Screen shot 这是屏幕截图 点击这里查看输出

Please any help will be highly appreciated.. 请任何帮助将不胜感激。

I don't see "services" element in your config file. 我在您的配置文件中看不到“服务”元素。 Please take a look at the below link to configure your service. 请查看以下链接以配置您的服务。 Configuring Services 配置服务

Another method is to create a wcf service using visual studio. 另一种方法是使用Visual Studio创建wcf服务。 Visual studio will generate appropriate config file for you. Visual Studio将为您生成适当的配置文件。 Then you can replace the methods, interface and configuration accordingly. 然后,您可以相应地替换方法,界面和配置。

I see that you are trying to return a List. 我看到您正在尝试返回列表。 I don't think you can pass List as return parameter. 我认为您不能将List用作返回参数。

Please check all methods on " http://localhost:50028/StudentService.svc " another suggestion, please remove "/" from uriTemplate. 请另外检查“ http:// localhost:50028 / StudentService.svc ”上的所有方法,请从uriTemplate中删除“ /”。 Just write "GetAllStudent" instead of "/GetAllStudent/". 只需编写“ GetAllStudent”而不是“ / GetAllStudent /”。

> <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>

As I look there is service and behaviors tags are missing from webconfig. 在我看来,webconfig中缺少服务和行为标签。

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

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