I have vb.net web api controller that I am trying to invoke but I'm getting back the following:
{"Message":"No HTTP resource was found that matches the request URI 'http://localhost:26944/api/employee/GetPerson/'.","MessageDetail":"No action was found on the controller 'Employee' that matches the request."}
This is the web controller:
Public Class EmployeeController
Inherits ApiController
Private ReadOnly dbContext As MyEntities
Sub New()
Me.dbContext = New MyEntities
End Sub
<HttpGet>
<ActionName("GetPerson")>
Function Person(ByVal missionaryId As Integer) As IPRS_Data.getPersInfoDetail_Result
Return Me.dbContext.getPersInfoDetail(missionaryId).First
End Function
End Class
WebApiConfig:
Public Shared Sub Register(ByVal config As HttpConfiguration)
' Web API configuration and services
' Web API routes
config.MapHttpAttributeRoutes()
config.Routes.MapHttpRoute(
name:="DefaultApi",
routeTemplate:="api/{controller}/{id}",
defaults:=New With {.id = RouteParameter.Optional}
)
Dim xmlFormat = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(Function(t) t.MediaType = "application/xml")
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(xmlFormat)
End Sub
I'm invoking the service using: appbase/api/employee/GetPerson/
Your method is decorated with HTTPGET and Actionname attribute. You don't need that if you have your method name starting with "Get" (like GetPerson). However, the Actionname is obsolete as it is not considered in your actual routing. Your routing is "api/{controller}/{id}". If you want your action name being considered you need to modify your routing to "api/{controller}/{action}/{id}". And if you want to have your id-param being considered per default routing you should rename the param in your method from missionaryId to just id.
Function Person(ByVal id As Integer) As IPRS_Data.getPersInfoDetail_Result
Return Me.dbContext.getPersInfoDetail(id).First
End Function
And that's the way how to invoke it (don't forget to pass an Id because there is no other "GET" method in your controller which works paramless.
appbase/api/employee/15
or
appbase/api/employee?id=15
and if you insist on missionaryId
appbase/api/employee?missionaryId=15
Related
Hi I need to create a class for return the data in WCF service. I followed the web at 5 simple steps to create your first RESTful service. However I get the error for . I searched the web and add the System.Runtime.Serialization.DataContractSerializer, Would someone tell me what should do. I am using VS2015 as the tool to build it. Thanks.
Imports System.Runtime.Serialization
Imports System.Collections.Generic
Imports System.Runtime.Serialization.DataContractSerializer
<DataContract>
Public Class Locations
<DataMember>
Public Property LocationName As String
<DataMember>
Public Property LocationID As Integer
End Class
Could you please share the error details with me?
As you know, we usually use the datacontract to transmit the complex data type which could be recognized by the client-side and server-side. so that the data could be serialized and transmitted normally between different platforms.
For the restful web service in WCF, we need to use the Webhttpbinding build the data channel and add the Webhttpbehavior to the service endpoint.
I have made a demo, wish it is useful to you.
Server-side.
Imports System.Runtime.Serialization
Imports System.ServiceModel
Imports System.ServiceModel.Description
Imports System.ServiceModel.Web
Module Module1
Sub Main()
Dim uri As New Uri("http://localhost:900")
Dim binding As New WebHttpBinding()
binding.CrossDomainScriptAccessEnabled = True
binding.Security.Mode = WebHttpSecurityMode.TransportCredentialOnly
binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None
Using sh As New ServiceHost(GetType(MyService), uri)
Dim se As ServiceEndpoint = sh.AddServiceEndpoint(GetType(IService), binding, uri)
se.EndpointBehaviors.Add(New WebHttpBehavior())
sh.Open()
Console.WriteLine("Service is ready")
Console.ReadLine()
sh.Close()
End Using
End Sub
<ServiceContract([Namespace]:="mydomain")>
Public Interface IService
<OperationContract>
<WebGet(ResponseFormat:=WebMessageFormat.Json)>
Function SayHello() As List(Of Product)
End Interface
Public Class MyService
Implements IService
Public Function SayHello() As List(Of Product) Implements IService.SayHello
Dim result = New List(Of Product)() From {
New Product With {
.Id = 1,
.Name = "Apple"
},
New Product With {
.Id = 2,
.Name = "Pear"
}
}
Return result
End Function
End Class
<DataContract([Namespace]:="mydomain")>
Public Class Product
<DataMember>
Public Property Id() As Integer
<DataMember>
Public Property Name() As String
End Class
End Module
Client.
$(function(){
$.ajax({
type:"GET",
url:"http://10.157.18.188:900/sayhello",
dataType:"jsonp",
success:function(d){
$.each(d,function(i,o){
console.log(o.Id);
console.log(o.Name);
})
}
})
})
Result.
Here is an official sample
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/how-to-create-a-basic-wcf-web-http-service
I'm beginner on stack overflow and in ASP.NET in general but I'll try to make my point clear here.
I'm developping a Web API in VB.NET but I'm stuck when I try to define routes.
I have for example these functions :
Public Function GetAllInformations() As IEnumerable(Of cl_information)
'return all informations
End Function
Public Function GetInformations(p_id As Int16) As IHttpActionResult
'return a specific informations
End Function
Public Function PutInformation(p_information As cl_information) As IHttpActionResult
'return the http statuscode depending on the update of the information
End Function
Public Function PostInformation(p_information As cl_information) As IHttpActionResult
'return the http statuscode depending on the post of the information
End Function
When I try this controller, using postman, I firsty check the GET method for the URI : /api/informations. The GetAllInformations() method is correctly triggered.
But when I try the GET method for a specific information item, on this kind of URI : /api/informations/i , the GetAllInformations() is also triggered.
I've got these informations from the event journal in visual studio :
"data": {
"baseType": "RequestData",
"baseData": {
"ver": 2,
"id": "12785441767974844366",
"name": "GET informations [id]",
"startTime": "2016-05-12T08:56:49.4044704+02:00",
"duration": "00:00:04.1740006",
"success": true,
"responseCode": "200",
"url": "http://localhost:51651/api/informations/i",
"httpMethod": "GET",
"properties": {
"DeveloperMode": "true"
}
}
I don't know why the request is not correctly routing to my GetInformations(p_id As Int16) function. Could you help me here please ?
FYI : I have this basic routes configuration :
Public Module WebApiConfig
Public Sub Register(ByVal config As HttpConfiguration)
' Configuration et services API Web
' Itinéraires de l'API Web
config.MapHttpAttributeRoutes()
config.Routes.MapHttpRoute(
name:="DefaultApi",
routeTemplate:="api/{controller}/{id}",
defaults:=New With {.id = RouteParameter.Optional}
)
End Sub
End Module
EDIT :
I tried to implement a method to handle both cases, with an optional argument, but the parameter isn't detected, event if I test the URI : /api/informations/i
Public Function GetInformations(Optional p_id As Int16 = 0) As IHttpActionResult
If p_id = 0 Then
'return all informations
End If
'return a specific information
End Function
after a day and a half on this, my mind is blowing but I finally found the problem.
I was using a wrong parameter name :
Public Function GetInformations(p_id As Int16) As IHttpActionResult
So I changed it by :
Public Function GetInformations(id As Int16) As IHttpActionResult
and it's working.
I am integrating an MVC project with my current Web Forms Application. I used Nuget to install MVC into the solution (based on some reading I did, which suggested doing this will add the binaries and configuration necessary). I then added a new MVC project into the solution and edited the Global.asax.vb file as following for MVC Routes:
Sub Application_Start(ByVal sender As Object, ByVal e As EventArgs)
' Code that runs on application startup
MVC.RouteConfig.RegisterRoutes(RouteTable.Routes)
End Sub
I configure my RouteConfig to ignore aspx files
Public Sub RegisterRoutes(ByVal routes As RouteCollection)
routes.IgnoreRoute("{resource}.axd/{*pathInfo}")
routes.IgnoreRoute("{*aspx}")
routes.MapRoute(
name:="Default",
url:="{controller}/{action}/{id}",
defaults:=New With {.controller = "Home", .action = "Index", .id = UrlParameter.Optional}
)
End Sub
My Web form routes work fine but my MVC one doesn't. How can I fix this?
Error:
HTTP Error 404.0 - Not Found
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
Controller:
Public Class HomeController
Inherits System.Web.Mvc.Controller
Function Index() As ActionResult
Return View()
End Function
Function About() As ActionResult
ViewData("Message") = "Your application description page."
Return View()
End Function
Function Contact() As ActionResult
ViewData("Message") = "Your contact page."
Return View()
End Function
End Class
I am trying to add a WCF service to my web control class project and allow my jquery client to consume the service. Ideally, I want to host the WCF service in the same project and allow a custom web control's (inside the same project) jQuery method consume the service. I'm not sure what I am doing wrong, but I am unable to make a connection between the jquery call and the service. Although there is no error, the break point on my service is never reached. Here is what I did:
Right Click on project and select Add
Select Web Service
This creates three files: Service1.vb, app.config, and IService1.vb
I edited the files to look like this:
Service1
Public Class Service1
Implements IService1
Public Function getUsers(ByVal prefixText As String) As List(Of String) Implements IService1.getUsers
Dim myList As New List(Of String)
With myList
.Add("Some String")
.Add("Another String")
End With
Return myList
End Function
End Class
IService1
Imports System.ServiceModel
<ServiceContract()>
Public Interface IService1
<OperationContract()> _
Function getUsers(ByVal prefixText As String) As List(Of String)
End Interface
And then I try to call it with the following jQuery:
$.ajax({
type: "POST",
url: 'Service1.vb/getUsers',
data: '{"prefixText":"' + getText + '"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert("success")
},
error: function (e) {
alert("Failed")
}
});
As I said, the break point on my getUsers function is never reached and the jquery success/failure alerts are never raised either. If someone can tell me how to reach the service and/or how to alert the error in my jQuery, I'd appreciate it. I left out the app.config stuff but can add it if it would be helpful.
thanks
This is a terrible misunderstanding in your code. By default, WCF uses Soap and Javascript/Jquery does not provide an easy way to invoke a SOAP Service.
You should use WCF Web HTTP Programming Model to expose WCF service operations to non-SOAP endpoints, like a REST-like service (can be called from JS)
Iy your are using WCF 4, this is quite easy.
Service Contract
<ServiceContract()>
Public Interface IService1
<OperationContract()>
<WebInvoke(BodyStyle:=WebMessageBodyStyle.Bare, RequestFormat:=WebMessageFormat.Json, ResponseFormat:=WebMessageFormat.Json)>
Function getUsers() As List(Of String)
End Interface
Service Implementation
Public Class Service1
Implements IService1
Public Function getUsers(ByVal prefixText As String) As List(Of String) Implements IService1.getUsers
Dim myList As New List(Of String)
With myList
.Add("Some String")
.Add("Another String")
End With
Return myList
End Function
End Class
Service1.svc
<%# ServiceHost Language="VB"
Service="MvcApplication2.Service1"
CodeBehind="Service1.svc.vb"
Factory="System.ServiceModel.Activation.WebServiceHostFactory" %>
I won't explain you everything here, and continue reading here or with this example
Also note that WCF REST is less popular today since because of ASP.NET Web Api. I don't believe that WCF REST is deprecated, but to expose something on the Web, Web Api sounds like a better solution.
I have a Web Method in Web service which is returning an XmlDocument. The Web service works fine when i am executing it and providing the necessary parameters.
I have created a proxy to this service in another application.proxy is created well and good.
Now the problem is,when i try to access the methods from that service its getting all the methods from the service but the return type of the method is showing as XmlNode instead of XmlDocument.
Let us say for example:
Service.asmx
public class DataService : System.Web.Services.WebService
{
[WebMethod]
public XmlDocument GetData(int ID)
{
//Code Here
}
}
Now i have one windows application which is using this service.
Created an object to the service through proxy.
DRService.DataService drService = new DRService.DataService();
Now i am trying to access the service methods.
drService.GetData(1)
The return type of the above method call should be XmlDocument but it is returning XmlNode as return type.
Any idea why the retun type is XmlNode?
This is the expected behavior.