I have a c # WebAPI where I currently have to functions..
App_Start
config.Routes.MapHttpRoute(
name: "DefaultApiWithKey",
routeTemplate: "api/{controller}/{passKey}"
);
config.Routes.MapHttpRoute(
name: "WithActionApiKey",
routeTemplate: "api/{controller}/{action}/{orderId}/{passKey}"
);
Controller
// This one returns Http 404
public IEnumerable<Order> GetAllOrders(string passKey)
{}
// This one works fine
public Order GetOrder(string orderId, string passKey)
{}
When I use the Getorder, it works. But the GetAllOrders does not work (I get an HTTP 404)
Why is that, what am I doing wrong?
Related
I have created angularjs scripts to call web api. My API config is as below,
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeHeaderValue("text/html"));
I am currently in the view <li>#Html.ActionLink("Create", "GB", "ProjectCreate" , new { area = "" }, null)</li> and from this page I am calling an api api/Users/GetUser but it throws an error that the api is not found and when I check in debug mode, the api being hit is of the uri ProjectCreate/api/Users/GetUser.
This is quite weird and I am not getting where the projectcreate appears from here.
it might be the name of your webapplication. Let me know how are you running your app.
I've got a self-hosted web api application with an angular front end, and I need to now start authenticating users via Azure Active Directory.
I've downloaded the SinglePageApp example and I've set this up and have it running successfully.
https://github.com/Azure-Samples/active-directory-angularjs-singlepageapp-dotnet-webapi
When applying the necessary changes to my own app, I can successfully redirect the user to the Azure login screen and get back the userProfile using adal.js/adal_angular.js. I'm getting 401 unauthorized errors whenever I call my API, however using Fiddler, I can see that the bearer token is added to the HTTP header in each call.
Here is my AdalAngular setup:
.config(["$httpProvider", "adalAuthenticationServiceProvider", ($httpProvider, adalProvider) => {
adalProvider.init(
{
instance: "https://login.microsoftonline.com/",
tenant: "<snip>.onmicrosoft.com",
clientId: "<snip>",
extraQueryParameter: "nux=1",
cacheLocation: "localStorage" // enable this for IE, as sessionStorage does not work for localhost.
},
$httpProvider);
Here is my startup.cs code:
public void Configuration(IAppBuilder appBuilder)
{
ConfigureWebApi(appBuilder);
ConfigureAuth(appBuilder);
ConfigureFileSystem(appBuilder);
appBuilder.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
}
private void ConfigureWebApi(IAppBuilder appBuilder)
{
// Configure Web API for self-host.
HttpConfiguration config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
private void ConfigureAuth(IAppBuilder app)
{
app.UseWindowsAzureActiveDirectoryBearerAuthentication(
new WindowsAzureActiveDirectoryBearerAuthenticationOptions
{
Tenant = ConfigurationManager.AppSettings["ActiveDirectoryTenant"],
Audience = ConfigurationManager.AppSettings["ActiveDirectoryApplicationId"]
});
}
private void ConfigureFileSystem(IAppBuilder appBuilder)
{
//Set the Welcome page to test if Owin is hosted properly
appBuilder.UseWelcomePage("/welcome.html");
appBuilder.UseErrorPage(new Microsoft.Owin.Diagnostics.ErrorPageOptions() { ShowExceptionDetails = true });
var physicalFileSystem = new PhysicalFileSystem(#".\wwwroot");
if (ConfigurationManager.AppSettings.AllKeys.Contains("ContentPath"))
{
var path = ConfigurationManager.AppSettings["ContentPath"];
physicalFileSystem = new PhysicalFileSystem(path);
}
FileServerOptions fileOptions = new FileServerOptions();
fileOptions.EnableDefaultFiles = true;
fileOptions.RequestPath = PathString.Empty;
fileOptions.FileSystem = physicalFileSystem;
fileOptions.DefaultFilesOptions.DefaultFileNames = new[] { "index.html" };
fileOptions.StaticFileOptions.FileSystem = fileOptions.FileSystem = physicalFileSystem;
fileOptions.StaticFileOptions.ServeUnknownFileTypes = true;
appBuilder.UseFileServer(fileOptions);
}
Where ActiveDirectoryTenant and ActiveDirectoryApplicationId are in my app.config and match what is configured in my angular adalProvider.init code exactly.
Finally, my ApiController looks like this:
[Authorize]
[RoutePrefix("api/connection")]
public class ServerConnectionController : ApiController
{
[Route("all")]
[HttpGet]
public HttpResponseMessage GetAllConnections()
{
HttpResponseMessage response;
try
{
string owner = ClaimsPrincipal.Current.FindFirst(ClaimTypes.NameIdentifier).Value;
var connections = _iDataAccess.GetAllConnections().ToList();
response = Request.CreateResponse(HttpStatusCode.OK, connections);
}
catch (Exception ex)
{
response = GetExceptionResponseMessage(ex);
}
return response;
}
}
As mentioned the HTTP request header captured by Fiddler looks ok, and the aud property on my ADAL.js userInfo.profile is the correct appid.
Any suggestions on what might be missing?
Note that this is not a native web based app, it's self-hosted, which means the web service is running on localhost as a windows service, and not in IIS.
I have configured the site to use HTTPS, but I get the same problem regardless of HTTP or HTTPS traffic.
Thanks for listening!
You need to declare the ConfigureAuth(appBuilder); as the first line in the Startup.cs Configuration method. You can find a good explanation here on why it need to be declared as the first.
I am completely new with angularjs using with webapi and I am probably going about it the wrong way but basically I want to search for a product by text(as I am executing the query in the database) as well as get a product by id for the purpose of updating the existing product.
The search by text I do as follow.
//productResource.js
(function () {
"use strict";
angular.module("common.services").factory("productResource", ["$resource", "appSettings", productResource])
function productResource($resource, appSettings) {
return $resource(appSettings.serverPath + "/api/products/:search");
}
}());
And in my webApi controller
public IEnumerable<Product> Get(string search)
{
var repository = new ProductRepository();
return repository.Restrieve(search);
}
public Product Get(int id)
{
Product product;
var repository = new ProductRepository();
if (id > 0)
{
product = repository.GetProductById(id);
}
else
{
product = repository.CreateProduct();
}
return product;
}
And then in my WebApiConfig:
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{search}",
defaults: new { search = RouteParameter.Optional }
);
The way it is setup now I manage to do searches by text.
How can I configure productResource.js and WebApiConfig to making provision for a search by id as well?
I would go with a slightly different routes here. In a RESTful API you have resources (products in your case). A resource is uniquely identified by id. So I would have the following route:
GET /products/:id
and if I wanted to search multiple products by text:
GET /products?search=xxxx
which would be just fine with the default routes:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
and now on the client side:
function productResource($resource, appSettings) {
return $resource(appSettings.serverPath + 'api/products/:id');
}
and to query:
productResource.query({ id: '123'});
productResource.query({ search: 'some search text'});
Here's a nice overview with examples of $resource.
Also make sure you have read the following blog post before the next time you try to put search texts (or any arbitrary data coming from clients) in the path portion of your routes instead of where they belong -> the query string.
I am just learning on how to use Web API with angular but I am having a few issues on retrieving data and I would appreciate it if someone could help me.
I have a controller called GetUserController with the following methods.
public class GetUserController : ApiController
{
[HttpGet]
public string GetUserName()
{
var user = "John Doe"
return user;
}
[HttpGet]
public string GetUserName2()
{
string user = "Jane Doe";
return user;
}
}
//Angular side of things
function getUser() {
return $http.get('/api/GetUser').then(function (data) {
return data;
});
}
The above code works fine and and returns the first user from the controller . however when I try to get the second by using the below angular code:
function getUser() {
return $http.get('/api/GetUser/GetUserName2').then(function (data) {
return data;
});
}
This does not work for some reason it says it can't find the GetUserName2 method. Am I missing something ? Please help?
EDIT: The error i'm getting is : Multiple actions were found that match the request
As #shammelburg has pointed out, this is as a result of Web.API not being able to match your request to a controller/method.
It's not so much that it's not RESTful, and has nothing to do with the verb you are using... it's just that an appropriate route map was not found.
Per the accepted answer, you can add another generic route map to enable the method of access you are attempting, however a more specific option exists using attribute routing:-
public class GetUserController : ApiController
{
[Route("api/getuser")]
[HttpGet]
public string GetUserName()
{
var user = "John Doe"
return user;
}
[Route("api/getuser/getusername2")]
[HttpGet]
public string GetUserName2()
{
string user = "Jane Doe";
return user;
}
}
And to enable the use of attribute routes, add this to your WebApiConfig class:-
config.MapHttpAttributeRoutes();
This method allows you to setup specific custom mappings of URLs to controllers/methods at the individual method level, without having to make a global route map that may conflict with something else in your application at a later date.
You can find more info on attribute routing here
Whilst the above will resolve the specific issue you are having, there would in practice be a different way to implement the example you gave:-
public class GetUserController : ApiController
{
[Route("api/user/{id}")]
[HttpGet]
public string GetUserName(int id)
{
// this would be replaced with some sort of data lookup...
var user = "unknown";
if (id == 1) {
user = "John Doe";
} else if (id == 2) {
user = "Jane Doe";
} // and so on...
return user;
}
}
In the above, the URL api/user/x where x is a number, e.g. api/user/1 will match the GetUserName method of the GetUserController and pass the number as an argument to the method.
This would be accessed using something like this in Angular:-
function getUser(id) {
return $http.get('/api/user/' + id).then(function (data) {
return data;
});
}
This is caused because it is not a true RESTful call which use HTTP verbs, GET, POST, PUT, DELETE.
The way to get your code to work is by altering your WebApiConfig.cs file.
From:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
To:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
As you can see we've added the {action} to the routeTemplate which makes this very much like a MVC Controller.
This allows you to call your API methods (GetUserName & GetUserName2) name like you are trying to do in your angular $http function.
Example:
return $http.get('/api/GetUser/GetUserName')
return $http.get('/api/GetUser/GetUserName2')
I cannot for the life of me understand why this isn't working.
I have a simple ASP.Net MVC Web API controller, with 2 get methods. I have an AngularJS service with 2 corresponding functions. The GetAllRisks works perfectly well. However, the GetRiskByID comes back with an error saying "No HTTP request was found that matches the request "http://localhost:49376/api/RiskApi/GetRiskByID/6" and "No action can be found on the RiskApi controller that matches the request."
The URL is being passed correctly. I have tried various options for the API routing but can't get anywhere. I am sure I am missing something simple but can't see it.
I would really appreciate any thoughts.
Thanks,
Ash
RiskApiController
public class RiskApiController : ApiController
{
private readonly IRiskDataService _riskDataService;
public RiskApiController(IRiskDataService riskDataService)
{
_riskDataService = riskDataService;
}
// GET api/RiskApi
[HttpGet]
public IEnumerable<IRisk> GetAllRisks()
{
return _riskDataService.GetAllRisks().Take(20);
}
// GET api/RiskApi/5
[HttpGet]
public IRisk GetRiskByID(int riskID)
{
IRisk risk = _riskDataService.GetRiskByID(riskID);
if (risk == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return risk;
}
}
service.js
app.service('OpenBoxExtraService', function ($http) {
//Get All Risks
this.getAllRisks = function () {
return $http.get("/api/RiskApi/GetAllRisks");
}
//Get Single Risk by ID
this.getRisk = function (riskID) {
var url = "/api/RiskApi/GetRiskByID/" + riskID;
return $http.get(url);
}
});
WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "ActionRoute",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Try changing your WebApiConfig class to:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
And change your param: riskID to id.
// GET: api/RiskApi/GetRiskByID/5
[HttpGet]
public IRisk GetRiskByID(int id)
{
IRisk risk = _riskDataService.GetRiskByID(id);
if (risk == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return risk;
}
Then, you could use:
// GET: api/RiskApi/GetAllRisks
// GET: api/RiskApi/GetRiskByID/5
...try junking your config's HttpRoute Mapping and introduce the route mapping with Attributes.
Since this is first-gen Web API, you'll need to pull in the AttributeRouting.WebAPI NuGet package, and you'll likely want to refer here(strathweb) for straightforward guidance on how to implement.
Note that you have a mapping problem in your current implementation on your {id} parameter: you declare it to be id in the route configuration, but then you identify it as riskID inside the controller's method; these need to match. Switch your controller's method to have its incoming routeParameter be named id. You could optionally switch your config to declare the {riskID} parameter in your routes, but that would couple your global configuration to the semantics of a specific controller and you'd likely need to implement more routing constraints to have other controllers not named "Risk" make sense.
public class RiskApiController : ApiController
{
private readonly IRiskDataService _riskDataService;
public RiskApiController(IRiskDataService riskDataService)
{
_riskDataService = riskDataService;
}
// GET api/RiskApi
[HttpGet]
[Route("api/RiskApi")]
public IEnumerable<IRisk> GetAllRisks()
{
return _riskDataService.GetAllRisks().Take(20);
}
// GET api/RiskApi/5
[HttpGet]
[Route("api/RiskApi/{id}")]
public IRisk GetRiskByID(int id)
{
IRisk risk = _riskDataService.GetRiskByID(id);
if (risk == null)
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotFound));
}
return risk;
}
}