Controller not filtering data in Breeze query in DotNetNuke Module - asp.net-web-api

I am trying to include the basic Breeze sample in a DotNetNuke module (it works fine in a standalone WebAPI project). To simplify things I remove the client and will just refer to the URL JSON calls I make in the Chrome browser.
I can see my metadata and a full list of items, eg:
http://www.dnndev.me/DesktopModules/framework/api/breeze/dare/metadata
http://www.dnndev.me/DesktopModules/framework/api/breeze/dare/todos
however, when I try to filter the list from the URL, it always returns the full list, e.g.
http://www.dnndev.me/DesktopModules/framework/api/breeze/dare/todos?=DareId%20eq%204
I think it is something to do with the way I have declared the MapHTTRoute. The problem is that DotNetNuke modules do not have a Global.ascx. I have copied the BreezeWebApiconfig.cs file into my App_Start folder and this does fire when I debug, however DotNetNuke uses mechanism for registering routes:
using DotNetNuke.Web.Api;
namespace SmartThinker.Modules.Framework
{
public class RouteMapper : IServiceRouteMapper
{
public void RegisterRoutes(IMapRoute mapRouteManager)
{
mapRouteManager.MapHttpRoute("framework", "BreezeApi", "breeze/{controller}/{action}", new[] { "SmartThinker.Modules.Framework.Controllers" });
}
}
}
I have read up on http://www.breezejs.com/documentation/web-api-controller#note01 and http://www.breezejs.com/documentation/web-api-routing but it seems that it's something to do with the way DNN registers the routes. Is there anyway to do this without using BreezeWebApiConfig.cs?
My controller code has the BreezeController attribute. (When I do connect the sample client to it I do get a list of items - it just does not filter, so I think it is something to with the OData Action filters. How can I debug where the problem is?
Update 1)
Here is the metadata:
http://www.ftter.com/desktopmodules/framework/api/dare/metadata
The GetUsers method:
http://www.ftter.com/desktopmodules/framework/api/dare/getusers
and the GetUsers method trying to filter by UserID (which doesn't work, which is the issue)
http://www.ftter.com/desktopmodules/framework/api/dare/getusers?=UserID%20eq%204
http://www.ftter.com/desktopmodules/framework/api/dare/GetUsersWithoutCors?=UserID%20eq%204 (this returns IQueryable)
Here is the controller:
[BreezeController]
public class DareController : DnnApiController
{
private readonly EFContextProvider<FrameworkContext> contextProvider = new EFContextProvider<FrameworkContext>();
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage Metadata()
{
var response = Request.CreateResponse(HttpStatusCode.OK, contextProvider.Metadata());
return GetResponseWithCorsHeader(response);
}
[AllowAnonymous]
[HttpGet]
public HttpResponseMessage GetUsers()
{
var userInfoController = new UserInfoController();
var response = Request.CreateResponse(HttpStatusCode.OK, userInfoController.GetUsers());
return GetResponseWithCorsHeader(response);
}
[AllowAnonymous]
[HttpGet]
public IQueryable<User> GetUsersWithoutCors()
{
return contextProvider.Context.Users;
}
}

The routing is not really a Breeze issue. How your server routes requests to your controller is up to you. What we do out-of-the-box is just one way among innumerable many.
You have the [BreezeController] attribute on your controller yes? Can you put a sample endpoint up where we could hit it. Might get some clues from that. Also post the controller. A tiny example should do ... something returning metadata and one method returning IQueryable.
Update 25 Jun 2013
I think you've discovered a bug in the way our [BreezeController] discovers methods returning IQueryable<T>.
The [BreezeController] attribute scans your Web API controller methods and (in effect) applies the [BreezeQueryable] attribute to methods returning IQueryable<T>.
[BreezeQueryable] is an extension of the Web API's [Queryable] that adds support for $select, $expand, and nested $orderby ... all missing from the current [Queryable].
I see now that your GetUsers() method returns HttpResponseMessage rather than IQueryable<User>. Let's assume that the userInfoController.GetUsers() method inside your method returns IQueryable<User>. Otherwise, the OData query parameters will not apply and we'll have to take this in a different direction. Moving along ...
I checked with v.1.3.6 of the Breeze.WebApi.dll and it does not detect that the HttpResponseMessage is wrapping IQueryable<T>. Therefore, it does not apply the client's OData query criteria (or any other OData modifiers for that matter). This shortcoming (in my opinion) is a bug. The following should be equivalent implementations:
[HttpGet]
public IQueryable<TodoItem> Todos() {
return _repository.Todos;
}
[HttpGet]
public HttpResponseMessage TodosWrapped()
{
return Request.CreateResponse(HttpStatusCode.OK, _repository.Todos);
}
The second, "wrapped" method does not respect the OData query parameters.
Fortunately, there is a workaround until we get this fixed. Just add the [BreezeQueryable] attribute explicitly ... as in:
[HttpGet]
[BreezeQueryable]
public HttpResponseMessage TodosWrapped()
{
return Request.CreateResponse(HttpStatusCode.OK, _repository.Todos);
}
I confirmed that this approach does work.
Thanks for finding this.
Use OData query syntax
A colleague also noticed that your query URL does not use the OData query syntax. You wrote:
... /todos?=DareId%20eq%204
when it should be
... /todos/?$filter=DareId%20eq%204
Make sure you use ?$filter=

Related

How can I resolve the error I am getting in web api?

**web-api**
As u can see I have to develop different api . For this I have created a MasterController. But I am getting an problem. I am using Postman for testing and I am getting the following problem. Please help me to resolve this issue. I am getting multiple match points. Please help me resolve the issue.
Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints.
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using VENUS.HRMS.API.Filters;
using VENUS.HRMS.DATA.Data;
using VENUS.HRMS.DATA.Models;
namespace VENUS.HRMS.API.Controllers
{
[ApiController]
[Route("[controller]")]
public class MasterController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpGet]
[AuthorizationFilter]
public IEnumerable<TblMstEmpRole> Get()
{
var emprole = new EmpRoleData().GetMstEmpRole();
return emprole;
}
[HttpGet]
[AuthorizationFilter]
public IEnumerable<TblMstState> GetState()
{
var state = new StateData().GetMstState();
return state;
}
[HttpGet]
[AuthorizationFilter]
public IEnumerable<TblMstCity> GetCity()
{
var city = new CityData().GetMstCity();
return city;
}
}
}
The issue is exactly what error says: The request matched multiple endpoints
Remember when calling an API, the function name does not matter. The function name is only for "Internal" use within your C# applicaiton. The name of the API endpoint correlates to it's route. This route is set with either the [Route()] attribute or within the [HttpGet()] attribute.
For example you have 3 functions:
[HttpGet]
public IEnumerable<TblMstEmpRole> Get()
[HttpGet]
public IEnumerable<TblMstState> GetState()
[HttpGet]
public IEnumerable<TblMstCity> GetCity()
The full route for these three functions respectively are:
Get --> /Master/
Get --> /Master/
Get --> /Master/
Yes all thee are the same. And that is the exact issue you are having. To fix this change the Route for your endpoints like this:
[HttpGet]
public IEnumerable<TblMstEmpRole> Get()
[HttpGet("State")]
public IEnumerable<TblMstState> GetState()
[HttpGet("City")]
public IEnumerable<TblMstCity> GetCity()
Now the routes will look like this:
Get --> /Master/
Get --> /Master/State
Get --> /Master/City
The rule is:
You can only have one route name per Http operation.
Different HTTP Methods
[HttpGet] is one of the attributes which has a GET method, however, there are many other methods such as POST, HEAD, PUT, OPTIONS, DELETE, CONNECT, TRACE and PATCH.
To utilize them through an API endpoint all you need to do is add it to the function. All the attributes have the [Http***] format. Example Post and Put will be:
[HttpPost]
[HttoPut]
And has mentioned a little above, you can only have one Route for each method. See examples below:
// PATH: GET --> /Master/
[HttpGet]
public IEnumerable<TblMstEmpRole> GETGet()
// PATH: POST --> /Master/
[HttpPost]
public IEnumerable<TblMstEmpRole> POSTGet()
The above example is VALID. Even though we have two functions with the same route, they do have different Http Methods and as such are uniquely identifiable.
Why Different Methods
Each method has it's own quirks and uses. Depending on the method, some things are allowed and some are not. When a client makes a query to a server and sends something, that is called a Http Request. The method for either getting or setting it is the Http Method, example GET, POST, PUT...
A Http Request has the following structure:
Headers
Parameters
Body
Footer
If we were to use the GET method, then you are telling the endpoint that it should ignore the Body of the request.
If we were to use the HEAD method then we are telling the endpoint that we are only interested in the Headers section of the request.
Now to figure out which to use and when can be tricky, but as a basic rule of thumb you can use this:
GET - You are only fetching data and not sending anything in the body
POST - When you are creating something in the database or sending data in the body
PUT - Similar to Post, but only when you are updating something
DELETE - When you are removing something.
These are the basic 4 any beginner to intermediate should be aware of. For more information on what method to use see: https://www.w3schools.com/tags/ref_httpmethods.asp

Web API Methods: Return IHttpActionResult Or IQueryable

I see most comments about Web API methods say they should return IHttpActionResult. When I add a Controller in Visual Studio and I select "Web API 2 Controller With Action For Entity Framework" it entered these two methods (along with POST, PUT, and DELETE). It uses IQueryable to return multiple records instead of IHttpActionResult. Which is correct and why?
// GET: api/Trades
public IQueryable<Trade> GetTrades()
{
return db.Trades;
}
// GET: api/Trades/5
[ResponseType(typeof(Trade))]
public IHttpActionResult GetTrade(int id)
{
Trade trade = db.Trades.Find(id);
if (trade == null)
{
return NotFound();
}
return Ok(trade);
}
Either is correct. The convenience of IQueryable is that you, well, can query it.
For example: You can use OData with WebAPI where some flexibility is required. You can then make your AJAX requests like mysite.com/odata/Orders?$filter=OrderID eq 1156.
Here is more on OData: http://www.odata.org/
It proved to be very handy for a dynamic search API with pagination support.

Additional GetXYZ methods in EntitySetController

I want to be able to have additional GetXYZ methods in my EntitySetController derived controller class. For example:
[HttpGet]
[Queryable]
public string GetAirportsWithinRadius(int airportId, int radius)
{
var resultAirports = GetAirportsWithinRadius2(airportId, radius);
return resultAirports;
}
This is what I have for config:
ActionConfiguration getAirportsWithinRadius = modelBuilder.Entity<Airport>().Collection.Action("GetAirportsWithinRadius");
getAirportsWithinRadius.Parameter<int>("airportId");
getAirportsWithinRadius.Parameter<int>("radius");
getAirportsWithinRadius.ReturnsCollectionFromEntitySet<Airport>("Airports");
I want this action to be composable just like the default Get Queryable action, but this would be an alternative that supports all odata parameters but additionally an airportId and radius. This would first filter airports by a radius search (this I know how to do - it's irrelevant to the question) and then return the Queryable so that it can be further filtered by odata params.
Everything I read says this would be an odata action and therefore must be a POST, but Get is also an action and that is a GET, so why not allow extended getters with additional parameters? Am I missing something? How do I accomplish what I want to get done?
I would call this from an ajax client as such:
GET /odata/Airports?$inlinecount=allpages&$top=25&airportId=2112&radius=50
as opposed to a regular odata GET:
GET /odata/Airports?$inlinecount=allpages&$top=25
Thanks
EDIT:
I understand now that this is an odata "function" and it is under consideration as a future feature. Let's forget for second the odata meaning of this. It is essentially a WebApi HttpGet that returns a Queryable, right? So, as long as I don't care about the metadata advertising of this "function", how can I make sure that it is a reachable HttpGet form a route perspective inside of an ODataController? The ODataController needs the MapODataRoute and can I additionally add non odata routes using additional MapHttpRoutes?
I ask this because it seems to me that I should be able to, but all my tries have failed (trying to hit the HttpGet through fiddler). I can find no examples on extending an ODataController with additional non-odata GETs. Can someone help me understand if and how this can be done with the example?:
[Queryable]
public IQueryable<Airport> Get()
{
return db.Airports;
}
[HttpGet]
[Queryable]
public string GetAirportsWithinRadius(int airportId, int radius)
{
var resultAirports = GetAirportsWithinRadius2(airportId, radius);
return resultAirports;
}
You are looking for OData Functions, which is not yet supported out of the box. We have an issue over here. You can up-vote it.
http://aspnetwebstack.codeplex.com/workitem/881

How should an API controller be tested now when HttpResponseMessage is created from the request?

Now when the constructor to create a response with HttpResponseMessage<T> and content is gone how should you do it if you want to test your controller? Request.CreateResponse<T> should be used instead and that is like such:
public HttpResponseMessage Post()
{
// Do Something
var response = Request.CreateResponse<SomeType>(System.Net.HttpStatusCode.OK, someObject);
return response;
}
Now to test a controller like this I have to stub the Request object since that is a property on the base class and I should use it to create the response, but that is not something I like and wonder if I can do it some other way?
From my experience, if you don't need to modify HttpResponseMessage, avoid to use it in ApiController, this will make your code simpler:
public SomeType Post()
{
// Do Something
return someObject;
}
In case it cannot be avoided, here is your answer:
ASP.NET WebApi unit testing with Request.CreateResponse
If you don't return an HttpResponseMessage then WebApi will call a MediaTypeFormatter for you to write the result to the response stream (i.e. it will use a MediaTypeFormatter to create an HttpResponseMessage for you). Many of the default implementations will do something similar to what you have above. Easiest solution is to return SomeType from your function and then utilize one of the built-in MediaTypeFormatters to do the conversion. You can test both solutions in isolation and together.

MVC Routes based on POST parameters

We have an a PHP application that we are converting to MVC. The goal is to have the application remain identical in terms of URLs and HTML (SEO and the like + PHP site is still being worked on). We have a booking process made of 3 views and in the current PHP site, all these view post back to the same URL, sending a hidden field to differentiate which page/step in the booking process is being sent back (data between pages is stored in state as the query is built up).
To replicate this in MVC, we could have a single action method that all 3 pages post to, with a single binder that only populates a portion of the model depending on which page it was posted from, and the controller looks at the model and decides what stage is next in the booking process. Or if this is possible (and this is my question), set up a route that can read the POST parameters and based on the values of the POST parameters, route to a differen action method.
As far as i understand there is no support for this in MVC routing as it stands (but i would love to be wrong on this), so where would i need to look at extending MVC in order to support this? (i think multiple action methods is cleaner somehow).
Your help would be much appreciated.
I have come upon two solutions, one devised by someone I work with and then another more elegant solution by me!
The first solution was to specify a class that extends MVcRouteHandler for the specified route. This route handler could examine the route in Form of the HttpContext, read the Form data and then update the RouteData in the RequestContext.
MapRoute(routes,
"Book",
"{locale}/book",
new { controller = "Reservation", action = "Index" }).RouteHandler = new ReservationRouteHandler();
The ReservationRouteHandler looks like this:
public class ReservationRouteHandler: MvcRouteHandler
{
protected override IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var request = requestContext.HttpContext.Request;
// First attempt to match one of the posted tab types
var action = ReservationNavigationHandler.GetActionFromPostData(request);
requestContext.RouteData.Values["action"] = action.ActionName;
requestContext.RouteData.Values["viewStage"] = action.ViewStage;
return base.GetHttpHandler(requestContext);
}
The NavigationHandler actually does the job of looking in the form data but you get the idea.
This solution works, however, it feels a bit clunky and from looking at the controller class you would never know this was happening and wouldn't realise why en-gb/book would point to different methods, not to mention that this doesn't really feel that reusable.
A better solution is to have overloaded methods on the controller i.e. they are all called book in this case and then define your own custome ActionMethodSelectorAttribute. This is what the HttpPost Attribute derives from.
public class FormPostFilterAttribute : ActionMethodSelectorAttribute
{
private readonly string _elementId;
private readonly string _requiredValue;
public FormPostFilterAttribute(string elementId, string requiredValue)
{
_elementId = elementId;
_requiredValue = requiredValue;
}
public override bool IsValidForRequest(ControllerContext controllerContext, System.Reflection.MethodInfo methodInfo)
{
if (string.IsNullOrEmpty(controllerContext.HttpContext.Request.Form[_elementId]))
{
return false;
}
if (controllerContext.HttpContext.Request.Form[_elementId] != _requiredValue)
{
return false;
}
return true;
}
}
MVC calls this class when it tries to resolve the correct action method on a controller given a URL. We then declare the action methods as follows:
public ActionResult Book(HotelSummaryPostData hotelSummary)
{
return View("CustomerDetails");
}
[FormFieldFilter("stepID", "1")]
public ActionResult Book(YourDetailsPostData yourDetails, RequestedViewPostData requestedView)
{
return View(requestedView.RequestedView);
}
[FormFieldFilter("stepID", "2")]
public ActionResult Book(RoomDetailsPostData roomDetails, RequestedViewPostData requestedView)
{
return View(requestedView.RequestedView);
}
[HttpGet]
public ActionResult Book()
{
return View();
}
We have to define the hidden field stepID on the different pages so that when the forms on these pages post back to the common URL the SelectorAttributes correctly determines which action method to invoke. I was suprised that it correctly selects an action method when an identically named method exists with not attribute set, but also glad.
I haven't looked into whether you can stack these method selectors, i imagine that you can though which would make this a pretty damn cool feature in MVC.
I hope this answer is of some use to somebody other than me. :)

Resources