I have a MVC 4 app in which i am wanting to use the web api to get my data. EDIT- this is a Single Page Application that started out with the Hot Towel Template. The problem is that I get the 404 resource not found when i try to call the controller from JSON. Here is my Controller-
Public Class CAApprovalController
Inherits ApiController
Public Function GetValues() As IEnumerable(Of String)
Return New String() {"value1", "value2"}
End Function
End Class
Here is my JSON call-
function getallCertificates() {
$.getJSON('api/CAApproval', function (data) {
allCertificates([]);
var temp = allCertificates();
data.forEach(function (p) {
var certificate = new Certificate(p.ClientID, p.RequestDate, p.UserName, p.StatusDescription, p.StatusCode, p.StatusDesc, p.CEOUserName);
temp.push(certificate);
});
allCertificates.valueHasMutated();
return allCertificates();
});
}
Here is the webapiconfig-
Public Class WebApiConfig
Public Shared Sub Register(ByVal config As HttpConfiguration)
config.Routes.MapHttpRoute( _
name:="DefaultApi", _
routeTemplate:="api/{controller}/{id}", _
defaults:=New With {.id = RouteParameter.Optional} _
)
'To disable tracing in your application, please comment out or remove the following line of code
'For more information, refer to: http://www.asp.net/web-api
config.EnableSystemDiagnosticsTracing()
'Use camel case for JSON data.
config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = New CamelCasePropertyNamesContractResolver()
End Sub
End Class
I am new to MVC and especially web api, and am thinking it is a newbie issue. Just not sure what the problem is. Is there a configuration or something i am missing? The project was created as a MVC 4 / web api application.
Found the problem at last. Turns out that Breezejs was the problem. My app is a single page application, and Breeze was one of the components of my SPA app (Breeze was installed as part of the Hot Towel template i was using). Not sure why, but when i uninstalled Breeze, the controllers i added to the project became visible. Something in the breeze scripts hi-jack the api routing.
Are you hosting your web api in IIS or running it from Visual Studio. If IIS, /LucasNetApp/api/caaproval. If Visual Studio, /api/caaproval.
You realize that "api/..." means "from the current relative location" right?
You probably want "/api/..." in your ajax call.
EDIT:
It's better to use a Url Helper.
$.getJSON('#Url.HttpRouteUrl("DefaultApi", new { controller = "CAApproval" })', function (data) {
Related
I am trying to hook up Swagger to a VB.Net REST API project. No matter what I try the app continues to return a 404 response when hitting the swagger/ui/index URL. Initially, on start-up I enter the following URL: http://localhost/ApiNameHere/Swagger.
IIS attempts to access (redirects to) http://localhost/swagger/ui/index. This returns a 404 response.
Swashbuckle was used to install Swagger
Locally, the app runs in IIS.
I have seen recommendations to delete the .vs folder. I have tried that, to no avail.
Here is the SwaggerConfig.vb file:
Public Class SwaggerConfig
Public Shared Sub Register(config As HttpConfiguration)
Dim thisAssembly = GetType(SwaggerConfig).Assembly
config.EnableSwagger(
Sub(c)
c.SingleApiVersion("v1", "ApiNameHere")
End Sub
).EnableSwaggerUi()
End Sub
End Class
Here is the relevant Startup.vb code :
Dim config = New HttpConfiguration()
config.MapHttpAttributeRoutes()
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", New With {RouteParameter.Optional})
SwaggerConfig.Register(config)
app.UseWebApi(config)
Any thoughts?
I am writing Angular 2 application by using Visual studio, and I took "ASP.NET Core Angular 2 Starter Application (Core)" template. So all things are already comes with created application.
I am trying to call web api in Angular 2 by using TypeScript as below code, But it's not calling, It's not hitting to the break point too.
public GetEntries(): Observable<RepeatList[]> {
console.log("Call 2");
return this.http.get('/breakout/GetEntries')
.map(this.ParseData)
.catch((error: any) => Observable.throw(error.json().error || 'Server error'));
}
When I put Api url in browser, It's giving me output. I am using below URL,
http://localhost:55482/breakout/GetEntries
My API is,
public class BreakoutController : BaseController{
[HttpGet]
public IEnumerable<RepeatList> GetEntries()
{
return _breakoutService.GetRepeatEntryNames("");
}
}
What things I ned to change to make it call my API, I am not adding api/ in front of api call.
I installed Swagger in my ASP.Net MVC Core project and it is documenting my API beautifully.
My co-worker asked me to install it in a full framework 4.6.1 project so I've done the following.
In Package Console Manager run:
Install-Package Swashbuckle
To get your Test Web API controller working:
1) Comment this out in the WebApi.config:
// config.SuppressDefaultHostAuthentication();
// config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
Now this URL:
http://localhost:33515/api/Test
brings back XML:
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>value1</string>
<string>value2</string>
</ArrayOfstring>
In Global.asax Register() I call:
SwaggerConfig.Register();
In AppStart.Swagger.Config Register() I put:
public class SwaggerConfig
{
public static void Register()
{
var thisAssembly = typeof(SwaggerConfig).Assembly;
GlobalConfiguration.Configuration
.EnableSwagger(c =>
{
c.SingleApiVersion("v1.0", "HRSA CHAFS");
c.IncludeXmlComments(GetXmlCommentsPath());
})
.EnableSwaggerUi(c =>
{});
}
private static string GetXmlCommentsPath()
{
var path = String.Format(#"{0}bin\Services.XML", AppDomain.CurrentDomain.BaseDirectory);
return path;
}
}
Now I get this error:
"A route named 'swagger_docsswagger/docs/{apiVersion}' is already in the route collection. Route names must be unique."
I've been stuck on this for hours.
How do you get rid of this?
This can happen when you re-name your .NET assembly. A DLL with the previous assembly name will be present in your bin folder. This causes the swagger error.
Delete your bin folder and re-build your solution.
This resolves the swagger error.
Swagger config uses pre-application start hook, so you don't need to call SwaggerConfig.Register() explicitly. Otherwise Register method is called twice.
[assembly: PreApplicationStartMethod(typeof(SwaggerConfig), "Register")]
in my case i added another project as refrence and that other project has swagger too.
i remove that refrence and move needed code to new project.
I solved the problem by deleting the SwaggerConfig.cs file from the App_Start folder as I had already created it manually.
Take a look at this link, here also has more useful information:
A route named 'DefaultApi' is already in the route collection error
In my experience the error occurs when you add reference to another project and that project is a service and it occurs on the SwaggerConfig of the referenced project. Removing project reference usually solve the problem, if you need to share classes I suggest you to create a specific project as Class Library and add its reference to both your services
I am using System.Web.Mvc.Controller for the UI and System.Web.Http.ApiController for the API in prototyping a web interface for large ERP application. I have figured out a way to make the UI somewhat extensible with the question Deploying un-compiled ASP.NET MVC Razor application. Now I am wondering, due to the strict nature of ApiController if there is some other class I should be considering for providing an open-ended interface for defining custom API transactions. Or is there some way to use ApiController in a more open-ended way where parameter count and type may be varied... perhaps by accepting an object parameter?
For Web API, you could try implementing a custom action selector using IHttpActionSelector interface:
public class CustomActionSelector : IHttpActionSelector
{
public override HttpActionDescriptor SelectAction(HttpControllerContext context)
{
var method = GetMethod(context);
return new ReflectedHttpActionDescriptor(GetController(method), method);
}
private MethodInfo GetMethod(HttpControllerContext context)
{
// Locate the target method using the extensibility framework of your choice
// (for example, MEF, pure reflection, etc.)
}
private HttpControllerDescriptor GetController(MethodInfo method)
{
return new HttpControllerDescriptor()
{
ControllerName = method.DeclaringType.Name,
ControllerType = method.DeclaringType
};
}
}
To register your new action selector place the following in your global.asax file under Application_Start:
var config = GlobalConfiguration.Configuration;
config.Services.Replace(typeof(IHttpActionSelector), new CustomActionSelector());
Hope this helps.
To make an ASP.NET web application extensible is very straightforward because ASP.NET searches the bin directory for controller classes in all assemblies there. So if the party providing customizations can simply compile their code into a DLL and drop it into the bin directory, your web application will pick up all their controllers as well as the controllers from the standard delivery. As an example, I created the following class in a standalone DLL that referenced System.Web.Http and System.Web.Mvc:
Public Class CustomTestController
Inherits ApiController
Public Function GetValues() As IEnumerable(Of String)
Return New String() {"value1", "value2"}
End Function
End Class
I simply compiled it and copied it to the bin directory of the location where my web application was deployed, and then I could access http://localhost/MyApplication/api/CustomTest/ and get back value1 and value2 in the expected response.
I'm having difficulties with accessing a WCF service. My service is
running in the same solution as the MonoDroid App and is hosted by visual
studio. I configured it as BasicHttp. The reference adds ok but at runtime
when I call the one simple test method, I get ;
System.Net.WebException
it's very simple this is web service
public class Service1 : System.Web.Services.WebService
{
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
}
and here is call
button.Click += delegate
{
localhost.Service1 se = new localhost.Service1();
button.Text= se.HelloWorld();
};
and error snapshot in attachment
I agree that you need to add more information. However, I responded to this question sometime ago and this is what I am doing for the WCF stuff and it's working great for me.
Using Soap in Shared Mono Library for WP 7 and Android
This might help out.
One other thing that I just thought of. Do you have the internet option in the network manifest selected as shown here:
http://docs.xamarin.com/#api/deki/files/1026/=RequiredPermissionsVS.png