I'm writing the below in VB.net for an Owin Controller. i'm trying to write the code for the GET Method and i get a Keyword can't be used as an identifier. How do i create a Get web method?
Public Class FactoryStatusController
Inherits ApiController
Public Function Get() As String
Return "TEst"
End Function
End Class
Try not to use verbs like "get" or "put" or something that your programming language might confuse with something else. By default the system will take your request as a HttpGet. There is many others you can use. I suggest you search for Action selectors and Action verbs for mvc 5 or which ever version you have
Get method
' GET: /Account/Login
<AllowAnonymous>
Public Function Login(returnUrl As String, id As String) As ActionResult
ViewData!ReturnUrl = returnUrl
End Function
Post method
' POST: /Account/Login
<HttpPost>
<AllowAnonymous>
<ValidateAntiForgeryToken>
Public Async Function Login(model As LoginViewModel, returnUrl As String, id As String) As Task(Of ActionResult)
Related
Using this example from the FluentValidation website, I'm converting the concept to VB.NET using my own classes. The part in interest to my issue is the Must(BeOver18), which calls the protected function. Note that this call doesn't pass a parameter to BeOver18:
public class PersonAgeValidator : AbstractValidator<Person> {
public PersonAgeValidator() {
RuleFor(x => x.DateOfBirth).Must(BeOver18);
}
protected bool BeOver18(DateTime date) {
//...
}
}
I created my own validator class in VB.NET like this, using the same principal as above but instead for a function called CustomerExists:
Public Class ContractValidator
Inherits AbstractValidator(Of ContractDTO)
Public Sub New()
RuleSet("OnCreate",
Sub()
RuleFor(Function(x) x.CustomerID).NotEmpty
' Compiler error here:
' BC30455 Argument not specified for parameter 'customerID'.....
RuleFor(Function(x) x.CustomerID).Must(CustomerExists)
End Sub
)
End Sub
Protected Function CustomerExists(customerID As Integer) As Boolean
Return CustomerService.Exists(customerID)
End Function
End Class
ISSUE: The line in VB.NET with .Must(CustomerExists) is giving the "Argument not specified for parameter 'customerID'..." compiler error. The C# example does not pass a parameter to BeOver18. I tried an additional anonymous in-line function to try to pass ContractDTO.CustomerID, but it doesn't work as it's not recognized:
' This won't work:
RuleFor(Function(x) x.CustomerID).Must(CustomerExists(Function(x) x.CustomerID))
I'm at a loss on how the C# example can call it's function without a parameter, but the VB.NET conversion cannot. This is where i need help.
Your CustomerExists function needs to be treated as a delegate. In order to do that, change the following:
Original
RuleFor(Function(x) x.CustomerID).Must(CustomerExists)
Update
RuleFor(Function(x) x.CustomerID).Must(AddressOf CustomerExists)
I have the following controller:
Public Class GuestController
Inherits ApiController
Public Function SaveValue(<FromUri> ByVal passedName As String) As Savedata
'Get guest data from database
Dim guestResult As New Savedata
guestResult.Name = passedName.ToLower()
Return guestResult
End Function
End Class
And I have the following model:
Public Class Savedata
Public Property ID As Integer
Public Property Name As String
End Class
Just as a test, I want to be able to call this API passing it a value of JOE and have the API return joe to me.
First I tried
http://localhost:12976/api/guest?a=JOE
But that gave me this error:
No HTTP resource was found that matches the request URI 'http://localhost:12976/api/guest?a=JOE'.
No action was found on the controller 'Guest' that matches the request.
Then I found that I needed to name the url parameter the same as the parameter I have defined in my ApiController function. So, for my second attempt, I sent in this:
http://localhost:12976/api/guest?passedName=JOE
But that gave me this error:
The requested resource does not support http method 'GET'.
So now I'm confused as I don't specify an http method at all.
Ideas? Suggestions?
Thanks.
By default if making a request from the browser, unless otherwise stated, the request will be a GET request
But as the name of the action is not following default naming conventions (like having a Get prefix), the framework is unable to infer which HTTP verb the action accepts.
Use the HttpGet attribute on the action to let the framework know that the action accepts HTTP GET requests
Public Class GuestController
Inherits ApiController
<HttpGet()> _
Public Function SaveValue(<FromUri> ByVal passedName As String) As Savedata
'Get guest data from database
Dim guestResult As New Savedata
guestResult.Name = passedName.ToLower()
Return guestResult
End Function
End Class
I am working on Web API 2 in vb.net and I am getting issue with GET method.
First of all I am able able to put HttpGet or AcceptVerbs on either class or action method
I don't have Routeconfig because I created Web API 2 employ template project.
Here my WebApiConfig file
Public Module WebApiConfig
Public Sub Register(ByVal config As HttpConfiguration)
' Web API configuration and services
' Web API routes
config.MapHttpAttributeRoutes()
config.Routes.MapHttpRoute(
name:="DefaultApi",
routeTemplate:="api/{controller}/{action}/{id}",
defaults:=New With {.id = RouteParameter.Optional}
)
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(New MediaTypeHeaderValue("text/html"))
End Sub
End Module
and api controller class
Public Class HomeController
Inherits ApiController
' GET api/values
'Public Function GetValues() As IEnumerable(Of String)
' Return New String() { "value1", "value2" }
'End Function
' GET api/values/5
Public Function ConcatValues(ByVal param1 As String,ByVal param2 As String) As String
Return "value"
End Function
End Class
but When I run url : http://localhost:43021/api/home/ConcatValues?param1=1¶m2=2
I am getting error :
{"Message":"The requested resource does not support http method
'GET'."}
Add the <HttpGet()> attribute to the action so that the convention based routing that you configured knows to associate the action with a GET request. Normally the convention inspects the action's name like GetConcatValues to determine by convention that it is a GET request. Since the example action is not employing that convention that the next option is to attach <HttpGet()> attribute to the action definition.
' GET api/home/concatvalues?param1=1¶m2=2
<System.Web.Http.HttpGet()>
Public Function ConcatValues(ByVal param1 As String,ByVal param2 As String) As String
Return "value"
End Function
I am using Rhino Mocks along with nUnit to attempt to test my function IsApprovable() on an object. The function I am testing relies on another object "UserManager" that needs to be passed in. I am attempting to mock an instance of UserManager so I can specify the result of another function GetApproverDependantsList()
My issue is that when I mock the object and pass it into the function I am testing I get the following InvalidCastException:
Unable to cast object of type 'Castle.Proxies.IUserManagerProxye15b431a53ca4190b7ffbdf5e241e2bb' to type 'MyNamespace.Users.UserManager'.
I am new to this so I am not really sure if I am doing things correctly... Here is the sample mocking code I am using:
Dim helper As New BookingManagerHelper()
Dim booking As Booking = GetDummyBooking() 'method to get a booking in suitable state
Dim parameters As Collection(Of Parameter) = GetDummyParameters() 'factory method, as above
Dim mockedUserManager = MockRepository.GenerateMock(Of Users.IUserManager)()
'I have created a dummy function called GetUserCollectionWithDependant() to create the results I need the mocked function to return...
mockedUserManager.Stub(Function(x) x.GetApproverDependantsList(-1)).[Return](GetUserCollectionWithDependant(1))
'It's the line below where I find my exception...
Assert.AreEqual(True, helper.IsApprovable(booking, mockedUserManager, parameters))
The function I am attempting to test looks like the following:
Public Function IsApprovable(ByVal Booking As Booking , ByVal UserManager As Users.UserManager, Optional ByVal Parameters As Collection(Of Parameter) = Nothing) As Boolean
'various logic checks are performed on the objects passed in
End Function
Some things to note:
UserManager implements the interface IUserManager
UserManager contains additional properties and functions that are not defined by the interface
UserManager also inherits from a base class (do I need to override base properties?)
I can post more code if needed. Thanks in advance.
I am no expert in VB.NET but IsApprovable expects a UserManager instance. The mock is of type IUserManager. Maybe you want to adjust IsApprovable to use a IUserManager instance.
first time on stackoverflow + ninject (IoC's)
I have a situation in which I have Business Objects Implemented in a way that they have Models in them... i.e.
Public Class Whatever
Implements IWhatEver
Public Property Id as Integer
Public Property Name as String
Public Function SetWhatEver() as Whatever
'Do Whatever Settings
End Function
End Class
I am using ninject for DI (Dependency Injection) however the issue was that I couldn't use an Interface as a model being passed in an action, therefore I am trying to make a custom modelbinder and want to use the bindingContext.ModelType to pass to ninject and ninject to resolve it for me and so I can do my binding with metadata
Public Overrides Function BindModel(controllerContext As ControllerContext, bindingContext As ModelBindingContext) As Object
Dim modelType = ninjectPleaseResolve(bindingContext.ModelType)
Dim metaData = ModelMetadataProviders.Current.GetMetadataForType(Nothing, modelType)
bindingContext.ModelMetadata = metadata
Return MyBase.BindModel(controllerContext, bindingContext)
End Function
I hope this makes sense... I have tried looking for answers BTW and nothing online is making sense to me, so please can you explain in simple terms..
EDIT
I am adding the controller code below to give you a better understanding of what I am trying to do.. I don't want to use the Whatever class instead I want to use the IWhatever in the controller for my processing... please see below an example...
Public Class MainController
Inherits System.Web.Mvc.Controller
Dim repository As IWhatever
Public Sub New(pWhatever As IWhatever)
repository = pWhatever
End Sub
Function Index(myValues As IWhatever) As ActionResult
'So I can process these values to my liking...
repository.SetWhatEver(myValues)
' and then perhaps other functions like...
repository.Save()
Return View()
End Function
I hope this makes a little sense now..
the issue was that I couldn't use an Interface as a model being passed
in an action
You shouldn't pass in services through the action method. You should pass services in through the constructor. This way your container can build up the controller and all related objects for you and this way you don't have to write a custom model binder.