Attribute Routing in ASP.NET Core OData 8.0 not working - asp.net-core

I have been attempting to follow this post to enable attribute routing in OData 8.0.10:
Attribute Routing in ASP.NET Core OData 8.0 RC
During development of v8 ODataRouteAttribute and ODataRoutePrefixAttribute have been removed and routing is supposed to follow regular ASP.NET Core attribute routing, however I cannot get this to work as described.
I register OData as follows:
// build edm:
model = builder.EntitySet<Stuff.PersonProfile>("personProfiles");
// startup.cs
odataOptions.Count().Filter().Expand().Select().OrderBy().SetMaxTop(3).AddRouteComponents("", model)
// person profiles controller:
[Route("personProfiles")]
public class PersonProfilesController : ODataController
{
[HttpGet("Person")]
IActionResult GetPerson(ODataQueryOptions<Stuff.PersonProfileService.Models.PersonProfile> options)
{
}
}
This creates the endpoint correctly and I can reach it:
APIStuff.Controllers.PersonProfilesController.GetPerson (Stuff.API)
GET personProfiles/Person
However no OData endpoint mapping is created. If I remove the attribute route on the GetPerson method, then it DOES. i.e.: I get OData returned in the payload of the personProfiles endpoint that it creates.
It appears this was possible in the 8.0 preview as described in the following:
Routing in ASP NET Core 8.0 Preview
Where clearly there are examples of using attribute routing on the controller and the method. e.g.:
[ODataRoutePrefix("Customers({id})")]
public class AnyControllerNameHereController : ODataController
{
[ODataRoute("Address")]
public IHttpActionResult GetAddress(int id)
{
//......
}
[ODataRoute("Address/City")]
public IHttpActionResult GetCity(int id)
{
//......
}
}
I can only assume this has been removed or I am missing a very big elephant in the room.

Since 8.0 RC, attribute routing is changed to use [Route] and [HttpGet], etc
From your description, ‘personProfiles’ is an entity set, and “Person” looks like a property defined by the type of “personProfiles”, right?
If that’s the case, based on OData spec, you should query a property from an entity (a single entity). It means you should specify the key/id.
You can put the key in [Route] or in [HttpGet].
// person profiles controller:
[Route("personProfiles")]
public class PersonProfilesController : ODataController
{
[HttpGet("{key}/Person")] // this will generater route as: ‘personProfiles/{key}/Person’. It’s key as segment.
IActionResult GetPerson(ODataQueryOptions<Stuff.PersonProfileService.Models.PersonProfile> options)
{
}
}
// person profiles controller:
[Route("personProfiles({key})")] // this will generater route as: ‘personProfiles({key})/Person’. It’s key in parenthesis.
public class PersonProfilesController : ODataController
{
[HttpGet("Person")]
IActionResult GetPerson(ODataQueryOptions<Stuff.PersonProfileService.Models.PersonProfile> options)
{
}
}
Thanks,
-Sam

Related

Asp.Versioning.Http AmbiguousMatchException: The request matched multiple endpoints on controllers

I am trying to achieve header based versioning on my controllers with Asp.Versioning.Http package version 6.4.0
it is supposed to be super simple here however i get AmbiguousMatchException: The request matched multiple endpoints exception
Here is my Program class
and my controllers defined like that:
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddApiVersioning(options => {
// options.ApiVersionReader = new HeaderApiVersionReader("api-version");
options.DefaultApiVersion = new ApiVersion(1.0);
options.AssumeDefaultVersionWhenUnspecified = true;
options.ReportApiVersions = true;
}).EnableApiVersionBinding();
builder.Services.AddMvc();
builder.Services.AddSwaggerGen();
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
// app.UseSwagger();
//app.UseSwaggerUI();
}
app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();
app.MapHealthChecks("/health/live");
app.MapControllers();
app.Run();
namespace Things.Service.Controllers.V1
{
[ApiController]
[ApiConventionType(typeof(DefaultApiConventions))]
[Route("[controller]")]
[Asp.Versioning.ApiVersion(1.0)]
public class ThingsController : ControllerBase
{
// controller logic
}
}
namespace Things.Service.Controllers.V2
{
[ApiController]
[ApiConventionType(typeof(DefaultApiConventions))]
[Route("[controller]")]
[Asp.Versioning.ApiVersion(2.0)]`your text`
public class ThingsController : ControllerBase
{
// controller logic
}
}
I get this exception:
Microsoft.AspNetCore.Routing.Matching.AmbiguousMatchException: The request matched multiple endpoints. Matches:
Things.Service.Controllers.V2.ThingsController.GetAllAsync (Things.Service)
Things.Service.Controllers.V1.ThingsController.GetAllAsync (Things.Service)
This is happening because you are missing AddMvc. Don't let the name fool you, this adds MVC Core, not the full MVC stack. Starting in 6.0, the new setup pivots on IApiVersioningBuilder so that all of the setup is in one place and, hopefully, easier to follow. If you're coming from earlier versions (e.g. <= 5.x), this might be a surprise. This change was necessary because AddApiVersioning is now the foundation for Minimal APIs, which doesn't include MVC Core or controller support. AddMvc adds those features.
services
.AddApiVersioning() // Asp.Versioning.Http : Core services and Minimal APIs
.AddMvc() // Asp.Versioning.Mvc : MVC Core
.AddApiExplorer() // Asp.Versioning.Mvc.ApiExplorer : API Explorer
.AddOData() // Asp.Versioning.OData : OData support
.AddODataApiExplorer(); // Asp.Versioning.OData.ApiExplorer : OData API Explorer
Since you're using MVC Core and controllers, you do not need EnableApiVersionBinding. MVC Core has support for Model Binders. AddMvc will register all those services. If you want to receive the incoming ApiVersion in your controller action, you need only add a parameter of type ApiVersion with the name of your choice. For example:
namespace Things.Service.Controllers.V1
{
[ApiVersion(1.0)]
[ApiController]
[ApiConventionType(typeof(DefaultApiConventions))]
[Route("[controller]")]
public class ThingsController : ControllerBase
{
[HttpGet]
public IActionResult Get(ApiVersion version) => Ok();
}
}
Minimal APIs do not have a way to support this type of model binding. EnableApiVersionBinding provides a way to make it work. It won't hurt anything if you've added it, but it's unnecessary.
Finally, it looks like you have included a version number in your namespaces. If this is indeed your setup, you might consider using the VersionByNamespaceConvention. This would negate the need to decorate controllers with [ApiVersion]. The API version would be derived from the namespace itself. For additional details, see the Version By Namespace Convention documentation.

Can't use Json() in asp.net core web api as it in asp.net core web

In asp.net core web I create a controller and I can use:
return Json(new {status=true});
but in asp.net core web API I can't do it.
In a controller:
[HttpGet("{id}")]
public JsonResult Get(int id)
{
}
I can not return Json()
How to use it?
Asp.Net Core Web API does provide support for wide varieties of response types, with Json being one among them. You can do that like shown below. Make sure you have all your required dependencies. You can learn about the dependencies from the documentation link I attached in this answer.
[HttpGet]
public IActionResult Get()
{
return Json(model);
}
You can also specify strict response formats using the [Produces] Filter on your controller.
Configuring Custom Formatters
You can also configure your own custom formatters in Asp.Net Web API project by calling the .AddFormatterMappings() from ConfigureServices method inside of your Startup.cs. This allows for a greater control on your content negotiation part and lets you achieve strict restrictions.
Please go through this documentation to understand further.
Using Responses with Status Codes
However, when using Web API, I suggest you use the helper methods that are built in so that your response becomes more expressive as it contains both the response content along with the status code. An example of how to do that is below
[HttpGet]
public ActionResult Get()
{
return Ok(_authors.List());
}
For a full list of helper methods available, you can take a look at the Controller.cs and ControllerBase.cs classes.
Asp.net core web api inherit from controllerBase, which doesn't contain a Json(Object) method. You should initialize a new JsonResult yourself in the action.
[HttpGet("{id}")]
public JsonResult Get(int id)
{
return new JsonResult(new { status = true });
}

Customaze API Attribute

Good afternoon, I study .NET CORE. How to create a custom attribute for the controller API? I want to allow requests to controllers from certain ip addresses.
In ASP. Net framework I created a custom attribute inheriting from "AuthorizeAttribute" then I just add my attribute to my controller.
I want that controller work from specific Ip address
Create attribute inherited from IAuthorizationFilter to have similar behavior to previous ASP.NET framework.
public class IpAuthorizationAttribute : AuthorizeAttribute, IAuthorizationFilter
{
public void OnAuthorization(AuthorizationFilterContext context)
{
if (/*ip not allowed*/)
{
//return 401 Unauthorized
context.Result = new UnauthorizedResult();
}
}
}
However, Microsoft recommends policy based authorization for ASP.NET Core.

Routing is not working for web api with realtions

I am creating web api using asp.net core. The api end point is logically mapped to resource's relations based on guidelines here
So my API looks like
http://tax.mydomain.com/api/v1/clients/1/batches/12/start
Where Client is parent of Batch, 1 is clientid and 12 is batchid, and Start is POST action method.
Here is the corresponding controller
public class TaxController : Controller
{
[HttpPost]
[Route("clients/{clientid}/batches/{batchid}/start")]
public void Start([FromRoute]string clientId, [FromRoute]string batchId,
[FromBody]IEnumerable<string> urls)
{
// do something
}
}
since api/v1 is common to all controllers i configured that in startup's Configure method. Also i want Home as default controller.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
app.UseMvc(routes =>
{
routes.MapRoute("default","api/v1/{controller=Home}/{action=Index}/{id?}");
});
}
However client is getting not found error for api http://tax.mydomain.com/api/v1/clients/1/batches/12/start
Any controller methods that do not have a route attribute use convention-based routing.
When you use [Route] attribute, you define attribute routing and so conventional routing is not used for that action/controller. Therefore, your controller is accessible by
http://tax.mydomain.com/clients/1/batches/12/start
As an option, you can use the fact, that attribute routes can be combined with inheritance. Set a Route attribute on the entire controller and this will work as route prefix (the same behavior as [RoutePrefix] attribute in WebApi):
[Route("api/v1")]
public class TaxController : Controller
{
}
More general example from routing documentation:
[Route("api/[controller]")]
public abstract class MyBaseController : Controller { ... }
public class ProductsController : MyBaseController
{
[HttpGet] // Matches '/api/Products'
public IActionResult List() { ... }
[HttpPost("{id}")] // Matches '/api/Products/{id}'
public IActionResult Edit(int id) { ... }
}
There are two things wrong with your setup
You call http://tax.mydomain.com/clients/1/batches/12/start but you don't have specified the controller name within it. This route looks for a controller named ClientsController. So the correct url would have to be http://tax.mydomain.com/tax/clients/1/batches/12/start instead
You seem to be using default MVC/Viewbased route, but your url suggest you use WebAPI.
When you use WebAPI to create a Rest service, you don't have any actions. Instead, actions map to the Http Verbs (GET (Read), PUT (update/replace), POST (insert), DELETE).
So for REST Services your default route should look like this instead: api/v1/{controller=Home}/{id?}

Trying to implement a Breeze controller in asp.net mvc

I am trying to implement a simple Breeze controller in Asp.Net MVC4, but can't seem to access it. Is it possibly conflicting with .Net's standard Web.Api ?
If my url is http://localhost:49479/api/values then I get a good return value from Web Api.
However if my url is http://localhost:49479/breeze/Breeze I get "Http 404" error "Resource not found".
If my url is http://localhost:49479/breeze/Breeze/5 I get error No HTTP resource was found that matches the request URI 'http://localhost:49479/breeze/Breeze/5'.
Your advice is greatly appreciate.
Here's what I have in ..Controllers/BreezeController.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Breeze.ContextProvider;
using Breeze.WebApi2;
using Newtonsoft.Json;
namespace RageSys.Controllers
{
[BreezeController]
public class BreeezeController : ApiController
{
// GET api/values
public string Get(int id)
{
return "value";
}
public IEnumerable<string> GetMtm(int id)
{
return new string[] { "value1", "value2" };
}
}
}
and in BreezeWebApiConfig.cs :
using System.Web.Http;
[assembly: WebActivator.PreApplicationStartMethod(
typeof(RageSys.App_Start.BreezeWebApiConfig), "RegisterBreezePreStart")]
namespace RageSys.App_Start {
///<summary>
/// Inserts the Breeze Web API controller route at the front of all Web API routes
///</summary>
public static class BreezeWebApiConfig {
public static void RegisterBreezePreStart() {
GlobalConfiguration.Configuration.Routes.MapHttpRoute(
name: "BreezeApi",
routeTemplate: "breeze/{controller}/{action}"
);
}
}
}
The result you are getting from your api/values request is not coming from the listed controller. You must have the default ValuesController and WebApiConfig (which defines a route that takes a parameter) still in your project.
You do not have a route for http://localhost:49479/breeze/Breeze/5. The third segment (currently 5) needs to be the name of an Action method. For you, that means GetMtm. You do not have a route that takes any parameters, so you'll get nothing from: http://localhost:49479/breeze/Breeze/GetMtm/5 unless you define such a route. You probably don't want to do this though, because Breeze coupled with Entity Framework will make life very easy. You should implement the simplest possible Breeze / Entity Framework application and see how it works from there.
If you are using parameters and using Breeze, then ensure you use the .withParameters({ ParameterName: "Fred"}) or .withParameters({ id: id-value}), for example, in your Breeze query and ensure the parameter name in your function to be called (GetMtm in your case) at the server matches the parameter name you are using at the client.