WCF Restful Client throwing "The remote server returned an unexpected response: (405) Method Not Allowed." - wcf-client

I am a newbie at WCF. I created a WCF restful service in VS2010 (WCF service appl). It was targeted for Framework 4.0. I hosted this service on local IIS with appl pool set for framework 4.0. When I call the appl methods from browser or fiddler, they work fine. Now, I created a client console based. When I call any method from client I get the following Communication Exception:
** remote server returned an unexpected response: (405) Method Not Allowed.**
Service Interface file:
namespace MyService
{
[ServiceContract]
public interface ITestService
{
[WebGet(UriTemplate = "GetDateTime")]
[OperationContract]
string GetDateTime();
[WebGet(UriTemplate = "GetName")]
[OperationContract]
string GetName();
}
}
Class that implements the above interface:
namespace MyService
{
public class TestService : ITestService
{
public string GetDateTime()
{
return DateTime.Now.ToString();
}
public string GetName()
{
return "MY name is KingKong";
}
}
}
Web.config file:
<system.serviceModel>
<services>
<service behaviorConfiguration="ServiceBehavior" name="MyService.TestService">
<endpoint address="" behaviorConfiguration="web" binding="webHttpBinding" bindingConfiguration="" contract="MyService.ITestService">
</endpoint>
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehavior">
<!-- 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>
</behaviors>
<serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
TestService.svc
<%# ServiceHost Language="C#" Debug="true" Service="MyService.TestService" CodeBehind="TestService.svc.cs" %>
Client app.config:
<system.serviceModel>
<behaviors>
<endpointBehaviors>
<behavior name="">
<webHttp />
</behavior>
</endpointBehaviors>
</behaviors>
<client>
<endpoint address="http://localhost/BestService/TestService.svc"
binding="webHttpBinding" bindingConfiguration="" contract="MyService.ITestService"
name="MyClientConfig" kind="" endpointConfiguration="" />
</client>
</system.serviceModel>
Client program calling proxy class
static void Main(string[] args)
{
TestServiceClient proxy = null;
try
{
proxy = new TestServiceClient();
Console.WriteLine("Test 1: List all products");
string sdatetime = proxy.GetName();
Console.WriteLine("Datetime: {0}", sdatetime);
Console.WriteLine();
// Disconnect from the service
proxy.Close();
}
catch (CommunicationException cex)
{
if (cex.InnerException != null)
{
Console.WriteLine("{0}", cex.InnerException.Message);
}
else
{
Console.WriteLine("General exception: {0}", cex.Message);
}
}
catch (Exception e)
{
if (e.InnerException != null)
{
Console.WriteLine("{0}", e.InnerException.Message);
}
else
{
Console.WriteLine("General exception: {0}", e.Message);
}
}
Console.WriteLine("Press ENTER to finish");
Console.ReadLine();
}
I added a service reference to the application and the Reference.cs file has following partial code:
namespace MyClient.MyService {
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
[System.ServiceModel.ServiceContractAttribute(ConfigurationName="MyService.ITestService")]
public interface ITestService {
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ITestService/GetDateTime", ReplyAction="http://tempuri.org/ITestService/GetDateTimeResponse")]
string GetDateTime();
[System.ServiceModel.OperationContractAttribute(Action="http://tempuri.org/ITestService/GetName", ReplyAction="http://tempuri.org/ITestService/GetNameResponse")]
string GetName();
}
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public interface ITestServiceChannel : MyClient.MyService.ITestService, System.ServiceModel.IClientChannel {
}
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.CodeDom.Compiler.GeneratedCodeAttribute("System.ServiceModel", "4.0.0.0")]
public partial class TestServiceClient : System.ServiceModel.ClientBase<MyClient.MyService.ITestService>, MyClient.MyService.ITestService {
public TestServiceClient() {
}
public TestServiceClient(string endpointConfigurationName) :
base(endpointConfigurationName) {
}
public TestServiceClient(string endpointConfigurationName, string remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public TestServiceClient(string endpointConfigurationName, System.ServiceModel.EndpointAddress remoteAddress) :
base(endpointConfigurationName, remoteAddress) {
}
public TestServiceClient(System.ServiceModel.Channels.Binding binding, System.ServiceModel.EndpointAddress remoteAddress) :
base(binding, remoteAddress) {
}
public string GetDateTime() {
return base.Channel.GetDateTime();
}
public string GetName() {
return base.Channel.GetName();
}
}
}
Please help me as I have spent nearly 2 days trying to figure out the problem in the client
Thanks

VS2010 doesnt have the ability to generate a proxy for a RESTFUL service as it does for a SOAP based service. So the solution is write your own proxy class which inherits from the ClientBase class and use the Channel to call the web methods of the service.

Related

No assembly found containing a Startup or [AssemblyName].Startup class

I've tried resolving this from answers in other and similar posts, but no luck.
I'm Using MVC 5, framework 4.8 latest VS2017.
Thanks
My Config is: (including other attempts)
<configuration>
<appSettings>
<!--<add key="owin:AutomaticAppStartup" value="false" />-->
<add key="owin:HandleAllRequests" value="true"/>
<!--<add key="owin:AppStartup" value="Api.xxx" />-->
</appSettings>
</configuration>
Startup class is:
[assembly: OwinStartupAttribute(typeof(Api.xxx.Startup))]
namespace Api.xxx
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// Allow all origins
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
….
}
}
}
and Api is:
namespace Api.xxx
{
[Route("values")]
public class ValuesController : ApiController
{
private static readonly Random _random = new Random();
public IEnumerable<string> Get()
{
var random = new Random();
return new[]
{
_random.Next(0, 10).ToString(),
_random.Next(0, 10).ToString()
};
}
}
}
I think you need to change
[assembly: OwinStartupAttribute(typeof(Api.xxx.Startup))]
to
[assembly: OwinStartup(typeof(Api.xxx.Startup))]
Reference: https://learn.microsoft.com/en-us/aspnet/aspnet/overview/owin-and-katana/owin-startup-class-detection

Use Java object in mule

I am using a java object which should return me an endpoint, then I want to invoke a service hosted at the specified endpoint. Please assist.
Below is my effort
In mule.xml
<spring:beans>
<spring:bean id="reqUrl" class="com.mule.sbus.drools.RequestUrl"
scope="singleton" />
</spring:beans>
<bpm:drools />
<http:listener-config name="NorthboundSingleEntrypoint"
host="0.0.0.0" port="8191" doc:name="HTTP Listener Configuration" />
<http:request-config name="HTTP_Request_Configuration"
host="acdc3a38cffc411e5a18606a62b4ee07-877599714.us-west-1.elb.amazonaws.com"
port="80" doc:name="HTTP Request Configuration" />
<flow name="sbusdroolsFlow">
<http:listener config-ref="NorthboundSingleEntrypoint"
path="/*" doc:name="HTTP" />
<set-variable variableName="requestUrl"
value="#[message.inboundProperties.'http.request.path']" doc:name="RequestUrl" />
<script:component doc:name="Script">
<script:script engine="groovy">
<![CDATA[
return requestUrl;
]]>
</script:script>
</script:component>
<bpm:rules rulesDefinition="routingRules.drl"
initialFacts-ref="reqUrl" />
<expression-transformer evaluator="groovy"
expression="message.getPayload().getObject()" doc:name="Expression" />
<logger message="#[groovy:message.getPayload().getObject()]" level="INFO"
doc:name="LoggerResp" />
</flow>
Below is my drools .drl
#default dialect for the semantic code will be MVEL
global org.mule.module.bpm.MessageService mule;
import com.mule.sbus.drools.RequestUrl
dialect "mvel"
declare RequestUrl
#role(event)
end
rule "test123"
lock-on-active
when
$url:RequestUrl(url=="test123")
then
#order.setDestination("WAREHOUSE_A");
modify($url){setEndPoint("test123")}
end
rule "test234"
lock-on-active
when
$url:RequestUrl(url=="test234")
then
#order.setDestination("WAREHOUSE_A");
modify($url){setEndPoint("test234")}
end
and my java class
package com.mule.sbus.drools;
public class RequestUrl {
private String url;
private String endPoint;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getEndPoint() {
return endPoint;
}
public void setEndPoint(String endPoint) {
/*if(endPoint=="test123")
this.endPoint = endPoint;
else*/
this.endPoint = "/checkcibil";
System.out.println("inside java :::: " + endPoint);
}
#Override
public String toString() {
// TODO Auto-generated method stub
return "url : " + url + " endPoint : " + endPoint;
}
}
As you can see I am invoking my setter from the drools file and once I get the string I want to print the same using
<logger message="#[groovy:message.getPayload().getObject()]" level="INFO"
doc:name="LoggerResp" />
but I don't know what should be the message value to use. Please assist
Got the answer,
As I am using groovy, have commented drools, and the updated the code as below
<script:component doc:name="Script">
<script:script engine="groovy">
<![CDATA[
reqUrl.setEndPoint(requestUrl);
String endpnt = reqUrl.getEndPoint();
message.setProperty('endpnt', endpnt,org.mule.api.transport.PropertyScope.INVOCATION);
]]>
</script:script>
</script:component>
<logger message="#[flowVars['endpnt']]" level="INFO" doc:name="LoggerResp" />
Using groovy I am invoking the setter and the call the getter to have the value in endpt variable. This can now be set as a property in the message and later we can retrieve the same (outside groovy script tags), using #[flowVars['endpnt']]

HTTP client with spring-integration

I need to write a simple HTTP client to make simple GET request and get JSON response using Spring integration.
Call fails with no message in exception: org.springframework.web.client.HttpServerErrorException: 500 Internal Server Error.
I tried debugging Spring code and did it successfully till I have source code, namely till
in the method AbstractMessageHandler.handleMessage(Message message)
abstract handleMessageInternal(Message message) has been called which threw
exception saying that request with
URL = http://example.com?q={q}&authKey={authKey}&rows={rows}&page={page}&filter={filter}
failed. URL looked exactly as I quoted, i.e. expressions have not been executed.
Payload in the message was always as it should be - instance if ZtInput with correct field values.
Could anyone give me an idea what to do?
Here is spring-integration-zt-context.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:int="http://www.springframework.org/schema/integration"
xmlns:int-http="http://www.springframework.org/schema/integration/http"
xmlns:oxm="http://www.springframework.org/schema/oxm"
xsi:schemaLocation="http://www.springframework.org/schema/integration/http http://www.springframework.org/schema/integration/http/spring-integration-http-2.1.xsd
http://www.springframework.org/schema/integration http://www.springframework.org/schema/integration/spring-integration-3.0.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/oxm http://www.springframework.org/schema/oxm/spring-oxm-3.0.xsd">
<int:channel id="InChannelZt"></int:channel>
<int:channel id="OutChannelZt"></int:channel>
<!-- Gateway Start -->
<int:gateway id="ZtGateway" default-request-timeout="5000" default-reply-timeout="5000"
default-request-channel="InChannelZt" service-interface="com.example.service.ZtService">
<int:method name="getResults" request-channel="InChannelZt" reply-channel="OutChannelZt" />
</int:gateway>
<int-http:outbound-gateway id="locationZtGateway"
request-channel="InChannelZt"
reply-channel="OutChannelZt"
url="${zt_url}?q={q}&authKey={authKey}&rows={rows}&page={page}&filter={filter}"
http-method="GET"
reply-timeout='5000'
expected-response-type="com.example.vo.ZtResponse">
<int-http:uri-variable name="q" expression="payload.getQ()"/>
<int-http:uri-variable name="authKey" expression="payload.getAuthKey()"/>
<int-http:uri-variable name="rows" expression="payload.getRows()"/>
<int-http:uri-variable name="page" expression="payload.getPage()"/>
<int-http:uri-variable name="filter" expression="payload.getFilter()"/>
</int-http:outbound-gateway>
and two classes mentioned in it:
import com.xxxx.vo.ZtInput;
import com.xxxx.vo.ZtResponse;
public interface ZtService {
ZtResponse getSearchResults(ZtInput ztInput);
}
Payload:
public class ZtInput {
private String q; //=pink
private String authKey = "baef7f8e39c53f852c8a14b7f6018b58";
private String rows="20";
private String page="1";
private String filter = "";
public ZtInputVO() {
}
public String getQ() {
return q;
}
public void setQ(String q) {
this.q = q;
}
public String getAuthKey() {
return authKey;
}
public void setAuthKey(String authKey) {
this.authKey = authKey;
}
public String getRows() {
return rows;
}
public void setRows(String rows) {
this.rows = rows;
}
public String getPage() {
return page;
}
public void setPage(String page) {
this.page = page;
}
public String getFilter() {
return filter;
}
public void setFilter(String filter) {
this.filter = filter;
}
}
The URI in the exception is the original (unexpanded URI); the expansion is performed into a different variable. (We should/will change that to log the expanded URI). But the bottom line is your server didn't like the expanded URI and returned a 500 internal server error.
You can use a network/tcp monitor (eclipse has one built in or you can use wireshark) to examine the actual URL sent to the server. You can also look at the server logs, if enabled.
Or, in the debugger, step down to line 415 (in the current source code - version 4.0.4) and examine realUri.
EDIT: The exception now includes the expanded URI (currently available in 4.0.5.BUILD-SNAPSHOT and 4.1.0.BUILD-SNAPSHOT).

Spring integration gateway "Dispatcher has no subscribers"

I am getting an exception Dispatcher has no subscribers on the outboundChannel and can't figure out why. I am sure its something simple, I have stripped back my code to a very simple sample below:
My context is:
<bean id="requestService"
class="com.sandpit.RequestService" />
<integration:channel id="inboundChannel" />
<integration:service-activator id="service"
input-channel="inboundChannel"
output-channel="outboundChannel"
ref="requestService"
method="handleRequest" />
<integration:channel id="outboundChannel" />
<integration:gateway id="gateway"
service-interface="com.sandpit.Gateway"
default-request-channel="inboundChannel"
default-reply-channel="outboundChannel" />
<bean class="com.sandpit.GatewayTester">
<property name="gateway"
ref="gateway" />
</bean>
My Java code is:
public interface Gateway {
String receive();
void send(String message);
}
public class RequestService {
public String handleRequest(String request) {
return "Request received: " + request;
}
}
public class GatewayTester implements ApplicationListener<ContextRefreshedEvent> {
private Gateway gateway;
public void setGateway(Gateway gateway) {
this.gateway = gateway;
}
#Override
public void onApplicationEvent(ContextRefreshedEvent event) {
gateway.send("Hello world!");
System.out.println("FROM SERVICE: " + gateway.receive());
}
}
Note: A breakpoint does tell me that the RequestService is actually handling the request.
receive() with no args needs the reply channel to be a PollableChannel See the documentation.
add <queue/> to the outboundChannel.
Alternatively, You could change your gateway method to be String sendAndReceive(String in) and all will work as expected (and you can even remove the outboundChannel altogether).

Unity Resolve<Interface1<Interface2>> issues

is it possible to resolve objects which use generics in unity only using interfaces.
class
public interface ItestObject<T>{ T Create();}
public class testObject<T> : ItestObject<T> where T: class, ICMSBasicTextData, new()
{
public testObject(){}
public T Create()
{
return new T();
}
}
xml config
<alias alias="testObject_I" type="JMJoinery.ItestObject`1, JMJoinery" />
<alias alias="testObject_C" type="JMJoinery.testObject`1[[JMJoinery.CMS.Data.CMSBasicTextData, JMJoinery]], JMJoinery" />
<alias alias="CMSBasicTextData_I" type="JMJoinery.CMS.Data.ICMSBasicTextData, JMJoinery" />
<alias alias="CMSBasicTextData_C" type="JMJoinery.CMS.Data.CMSBasicTextData, JMJoinery" />
<register name="CMSBasicTextData_R" type="CMSBasicTextData_I" mapTo="CMSBasicTextData_C" />
<register name="test" type="testObject_I" mapTo="testObject_C" />
when i try to resolve:
var o2 = JMJoinery.Global.Container.Resolve<ItestObject<ICMSBasicTextData>>();
this error occurs:
"Unable to cast object of type 'JMJoinery.testObject1[JMJoinery.CMS.Data.CMSBasicTextData]' to type 'JMJoinery.ItestObject1[JMJoinery.CMS.Data.ICMSBasicTextData]'."
Using
Container.Resolve<ItestObject<CMSBasicTextData>>();
works, but is it possible to resolve using the interface only
Container.Resolve<ItestObject<ICMSBasicTextData>>();
instead?
Interface and Implementation
public interface ILookupDataReader<T>
{
string LookupTypeID { get; }
}
public class CountryDataReader: ILookupDataReader<ICountry>
{
string ILookupDataReader<ICountry>.LookupTypeID
{
get { return Enum.GetName(typeof(LookupTypeOptions), LookupTypeOptions.Country); }
}
}
Registration
<alias alias="ILookupDataReader" type="Co.Application.Shared.Core.BusinessObject.ILookupDataReader`1,Co.Shared.Impl"/>
<alias alias="ICountry" type="Co.Application.Shared.Core.BusinessObject.Lookup.ICountry, Co.Shared.Impl"/>
<register type="ILookupDataReader[ICountry]" mapTo="Co.Application.Shared.Core.BusinessObject.Lookup.CountryDataReader,Co.Shared.Impl">
<lifetime type="singleton"/>
</register>
Usage
[Dependency]
public ILookupDataReader<ICountry> CountryLookup { get; set; }

Resources