내 RESTful 웹 서비스에 대한 ac # 클라이언트 응용 프로그램을 만들려고합니다.
ServiceReference1
클라이언트 응용 프로그램에 웹 참조 ( )를 추가 했지만 'UserService1.svc'에 대한 끝점 구성이 존재하지 않는다는 오류가 발생합니다.
Rest Service를 사용할 때 'add service reference'가 필요한 모든 구성을 생성하지 않는다는 것을 알고 있지만 실제로 어디에서 잘못 가고 있는지 알 수 없습니다!
여기 내 파일이 있습니다
클라이언트 애플리케이션
namespace WebServiceClient
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
UserService1Client webService;
List<User> userList = new List<User>();
public MainWindow()
{
InitializeComponent();
webService = new UserService1Client();
serviceMethods();
}
private void serviceMethods()
{
string[] results = webService.GetUsersNames();
}
}
}
고객 - web.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.serviceModel>
<bindings>
<basicHttpBinding>
<binding name="BasicHttpBinding_IUserService1" />
</basicHttpBinding>
</bindings>
<client>
<endpoint address="http://localhost:53215/UserService1.svc" binding="basicHttpBinding"
bindingConfiguration="BasicHttpBinding_IUserService1" contract="ServiceReference1.IUserService1"
name="BasicHttpBinding_IUserService1" />
</client>
</system.serviceModel>
</configuration>
서비스-Web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
</configSections>
<system.web>
<compilation debug="true" targetFramework="4.0">
</compilation>
</system.web>
<system.serviceModel>
<services>
<service name="WcfRestSample.UserService1">
<endpoint address="" contract="WcfRestSample.IUserService1" binding="webHttpBinding" behaviorConfiguration="restBehavior"/>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="restBehavior">
<webHttp/>
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior>
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="true" />
</behavior>
</serviceBehaviors>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
<connectionStrings>
<add name="cs4_databaseEntities" connectionString="metadata=res://*/cs4_model.csdl|res://*/cs4_model.ssdl|res://*/cs4_model.msl;provider=System.Data.SqlClient;provider connection string="data source=.\SQLEXPRESS;attachdbfilename=|DataDirectory|\cs4_database.mdf;integrated security=True;user instance=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
IUserService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
namespace WcfRestSample
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IUserService1" in both code and config file together.
[ServiceContract]
public interface IUserService1
{
[OperationContract]
[WebGet(ResponseFormat = WebMessageFormat.Xml)]
List<string> GetUsersNames();
}
}
UserService1.svc
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WcfRestSample
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "UserService1" in code, svc and config file together.
// NOTE: In order to launch WCF Test Client for testing this service, please select UserService1.svc or UserService1.svc.cs at the Solution Explorer and start debugging.
public class UserService1 : IUserService1
{
public List<string> GetUsersNames()
{
using (cs4_databaseEntities entities = new cs4_databaseEntities())
{
return entities.Users.Select(user => user.Name).ToList();
}
}
}
}
누군가가 나를 도울 수 있기를 바랍니다 !!
먼저 RESTFUL 서비스의 경우 basichttpbinding이 아닌 webhttpbinding을 선언해야합니다 (SOAP 서비스 용). REST 서비스에 이러한 구성이 있어야합니다.
1) 서비스 및 엔드 포인트 선언
<services>
<service name="SparqlService.SparqlService" behaviorConfiguration="ServiceBehavior">
<endpoint binding="webHttpBinding" contract="SparqlService.ISparqlService" behaviorConfiguration="webHttp" />
</service>
</services>
서비스 이름은 [프로젝트 이름]입니다. [서비스 이름] 동작 구성은 다음 단계에서 선언하는 동작과 동일한 이름입니다. REST로 원하므로 바인딩은 webHttpBinding이어야합니다. SOAP를 원하는 경우 basicHttpBinding Contract가 [프로젝트 이름]으로 선언합니다. [인터페이스 이름] 끝점의 동작 구성은 다음 단계에서 선언하는 이름이됩니다.
2) 서비스 동작 선언 (일반적으로 기본값)
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
동작 이름은 무엇이든 될 수 있지만 1 단계에서 선언 한 BehaviorConfiguration과 일치하는 데 사용됩니다. 나머지는 그대로 둡니다.
3) 엔드 포인트 동작을 Delcare
<endpointBehaviors>
<behavior name="webHttp">
<webHttp />
</behavior>
</endpointBehaviors>
동작 이름은 무엇이든 될 수 있지만 엔드 포인트의 behaviorConfiguration과 일치하는 데 사용됩니다.
결국 이것은 간단한 REST 서비스에 대한 web.config의 모습입니다.
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
</system.web>
<system.serviceModel>
<services>
<service name="SparqlService.SparqlService" behaviorConfiguration="ServiceBehavior">
<endpoint binding="webHttpBinding" contract="SparqlService.ISparqlService" behaviorConfiguration="webHttp" />
</service>
</services>
<behaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
<behavior>
<!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
<serviceMetadata httpGetEnabled="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 name="webHttp">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
</system.serviceModel>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
</configuration>
web.config가 완료된 후 이것은 샘플 WCF REST 서비스 및 해당 C # 클라이언트입니다.
POST 또는 PUT를 통해 데이터를 보내려면 WCF 서비스에 따라 데이터를 올바르게 구성해야합니다. 기본적으로 필요한 것은 다음과 같습니다 (애플리케이션의 POST를 PUT으로 변경하기 만하면됩니다).
1) WCF 서비스 인터페이스
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "GetData",
RequestFormat = WebMessageFormat.Xml,
BodyStyle = WebMessageBodyStyle.Bare)]
string GetData(DataRequest parameter);
2) WCF 서비스 구현
public string GetData(DataRequest parameter)
{
//Do stuff
return "your data here";
}
3) WCF 서비스의 데이터 계약 (이 경우 DataRequest)
[DataContract(Namespace = "YourNamespaceHere")]
public class DataRequest
{
[DataMember]
public string ID{ get; set; }
[DataMember]
public string Data{ get; set; }
}
4) 데이터를 보내는 클라이언트는 데이터가 올바르게 구성되어 있어야합니다! (이 경우 C # 콘솔 앱)
static void Main(string[] args)
{
ASCIIEncoding encoding = new ASCIIEncoding();
string SampleXml = "<DataRequest xmlns=\"YourNamespaceHere\">" +
"<ID>" +
yourIDVariable +
"</ID>" +
"<Data>" +
yourDataVariable +
"</Data>" +
"</DataRequest>";
string postData = SampleXml.ToString();
byte[] data = encoding.GetBytes(postData);
string url = "http://localhost:62810/MyService.svc/GetData";
string strResult = string.Empty;
// declare httpwebrequet wrt url defined above
HttpWebRequest webrequest = (HttpWebRequest)WebRequest.Create(url);
// set method as post
webrequest.Method = "POST";
// set content type
webrequest.ContentType = "application/xml";
// set content length
webrequest.ContentLength = data.Length;
// get stream data out of webrequest object
Stream newStream = webrequest.GetRequestStream();
newStream.Write(data, 0, data.Length);
newStream.Close();
//Gets the response
WebResponse response = webrequest.GetResponse();
//Writes the Response
Stream responseStream = response.GetResponseStream();
StreamReader sr = new StreamReader(responseStream);
string s = sr.ReadToEnd();
return s;
}
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다