I have ASP.net Web Api project and I decided that it was time to support versioning. I am using official Microsoft Nuget to support versioning (more info here), and I decided to version by namespace (as exampled here).
Unfortunately I cannot get code to work. If I call my method like this:
http://localhost:7291/api/Saved/GetNumberOfSavedWorkoutsForUser?api-version=2.0
I get error:
Multiple types were found that match the controller named 'Saved'. This can happen if the route that services this request ('api/{controller}/{action}/{id}') found multiple controllers defined with the same name but differing namespaces, which is not supported.
And if I call it like this: http://localhost:7291/v2/Saved/GetNumberOfSavedWorkoutsForUser
I get error 404:
The resource you are looking for has been removed, had its name changed, or is temporarily unavailable.
I am not sure what I am doing wrong. Here is my code:
Startup.cs
public void Configuration(IAppBuilder app)
{
var configuration = new HttpConfiguration();
var httpServer = new HttpServer(configuration);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
// reporting api versions will return the headers "api-supported-versions" and "api-deprecated-versions"
configuration.AddApiVersioning(o =>
{
o.AssumeDefaultVersionWhenUnspecified = true;
o.ReportApiVersions = true;
o.DefaultApiVersion = ApiVersion.Default;
});
configuration.Routes.MapHttpRoute(
"VersionedUrl",
"v{apiVersion}/{controller}/{action}/{id}",
defaults: null,
constraints: new { apiVersion = new ApiVersionRouteConstraint() });
configuration.Routes.MapHttpRoute(
"VersionedQueryString",
"api/{controller}/{action}/{id}",
defaults: null);
app.UseWebApi(httpServer);
ConfigureAuth(app);
}
Saved Controller (v1)
namespace Master.Infrastructure.Api.Controllers
{
[Authorize]
[RoutePrefix("api/Saved")]
[ApiVersion("1.0")]
public class SavedController : ApiController
{
private readonly IUserService _userService;
public SavedController(IUserService userService)
{
_userService = userService;
}
[HttpGet]
[ActionName("GetNumberOfSavedWorkouts")]
public async Task<NumberOfSavedWorkouts> GetNumberOfSavedWorkouts()
{
var numOfSavedWorkouts = new NumberOfSavedWorkouts
{
CurrentNumberOfSavedWorkouts =
await _userService.GetNumberOfSavedWorkoutsForUserAsync(User.Identity.GetUserId())
};
return numOfSavedWorkouts;
}
}
}
Saved Controller (v2)
namespace Master.Infrastructure.Api.V2.Controllers
{
[Authorize]
[ApiVersion("2.0")]
[RoutePrefix("v{version:apiVersion}/Saved")]
public class SavedController : ApiController
{
private readonly ISavedWorkoutService _savedWorkoutService;
public SavedController(ISavedWorkoutService savedWorkoutService)
{
_savedWorkoutService = savedWorkoutService;
}
[ActionName("GetNumberOfSavedWorkoutsForUser")]
public async Task<IHttpActionResult> GetNumberOfSavedWorkoutsForUser()
{
var cnt = await _savedWorkoutService.CountNumberOfSavedWorkoutsForUser(User.Identity.GetUserId());
return Ok(cnt);
}
}
}
Your routes are incorrect. I strongly discourage you from mixing routing styles unless you really need to. It can be very difficult to troubleshoot.
There are several things going on here:
You have configurations to version both by query string and URL segment, which one do you want? I would choose only one. The default and my recommendation would be to use the query string method.
Your convention-based route is different from the attribute-base route
Since you have RoutePrefixAttribute defined, it appears you prefer the attribute-routing style. I would remove all convention-based routes (ex: configuration.Routes.MapHttpRoute).
In your convention, the route template:
v{apiVersion}/{controller}/{action}/{id}
but in your attribute it's:
api/Saved
Neither of these will match your expected routes:
http://localhost:7291/api/Saved/GetNumberOfSavedWorkoutsForUser
http://localhost:7291/v2/Saved/GetNumberOfSavedWorkoutsForUser
For the query string method using route attributes, things should look like:
configuration.AddApiVersioning(o => o.ReportApiVersions = true);
namespace Master.Infrastructure.Api.Controllers
{
[Authorize]
[ApiVersion("1.0")]
[RoutePrefix("api/Saved")]
public class SavedController : ApiController
{
private readonly IUserService _userService;
public SavedController(IUserService userService) => _userService = userService;
[HttpGet]
[Route("GetNumberOfSavedWorkouts")]
public async Task<IHttpActionResult> GetNumberOfSavedWorkouts()
{
var userId = User.Identity.GetUserId();
var count = await _userService.GetNumberOfSavedWorkoutsForUserAsync(userId);
return Ok(new NumberOfSavedWorkouts(){ CurrentNumberOfSavedWorkouts = count });
}
}
}
namespace Master.Infrastructure.Api.V2.Controllers
{
[Authorize]
[ApiVersion("2.0")]
[RoutePrefix("api/Saved")]
public class SavedController : ApiController
{
private readonly ISavedWorkoutService _savedWorkoutService;
public SavedController(ISavedWorkoutService savedWorkoutService) => _savedWorkoutService = savedWorkoutService;
[HttpGet]
[Route("GetNumberOfSavedWorkoutsForUser")]
public async Task<IHttpActionResult> GetNumberOfSavedWorkoutsForUser()
{
var userId = User.Identity.GetUserId();
var count = await _savedWorkoutService.CountNumberOfSavedWorkoutsForUser(userId);
return Ok(count);
}
}
}
The following should then work:
http://localhost:7291/api/Saved/GetNumberOfSavedWorkouts?api-version=1.0
http://localhost:7291/api/Saved/GetNumberOfSavedWorkoutsForUser?api-version=2.0
I hope that help.s
I'm exploring the use of DryIoc in a .NET WebAPI application and have noticed a strange behavior with the initialization steps. In a simple test webapi application, I have the following DryIoc registration class which gets called immediately after the WebApi config registration.
public class DryIocConfig
{
public static void Register(HttpConfiguration config)
{
var c = new Container().WithWebApi(config);
c.Register<IWidgetService, WidgetService>(Reuse.Singleton);
c.Register<IWidgetRepository, WidgetRepository>(Reuse.Singleton);
}
}
And the following WebApi controller:
public class ValuesController : ApiController
{
private readonly IWidgetService _widgetService;
public ValuesController(IWidgetService widgetService)
{
_widgetService = widgetService;
}
// GET api/values
public IEnumerable<Widget> Get()
{
return _widgetService.GetWidgets();
}
}
This seems to work fine, but in experimenting with was seems to me to be the identical, but written a little more verbose, code I get an error.
public class DryIocConfig
{
public static void Register(HttpConfiguration config)
{
var c = new Container();
c.WithWebApi(config); // Now separate statement rather than chained.
c.Register<IWidgetService, WidgetService>(Reuse.Singleton);
c.Register<IWidgetRepository, WidgetRepository>(Reuse.Singleton);
}
}
The exception I get is the following (as JSON):
{
"Message" : "An error has occurred.",
"ExceptionMessage" : "An error occurred when trying to create a controller of type 'ValuesController'. Make sure that the controller has a parameterless public constructor.",
"ExceptionType" : "System.InvalidOperationException",
"StackTrace" : " at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()",
"InnerException" : {
"Message" : "An error has occurred.",
"ExceptionMessage" : "Type 'IOCContainerTest.DryLoc.Controllers.ValuesController' does not have a default constructor",
"ExceptionType" : "System.ArgumentException",
"StackTrace" : " at System.Linq.Expressions.Expression.New(Type type)\r\n at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"
}
}
Is this something odd with DryIoc, or is this a C# nuance that I've just never come across?
This is because .WithWebApi() is an extension method per the source.
public static IContainer WithWebApi(this IContainer container, HttpConfiguration config,
IEnumerable<Assembly> controllerAssemblies = null, IScopeContext scopeContext = null,
Func<Type, bool> throwIfUnresolved = null)
{
container.ThrowIfNull();
if (container.ScopeContext == null)
container = container.With(scopeContext: scopeContext ?? new AsyncExecutionFlowScopeContext());
container.RegisterWebApiControllers(config, controllerAssemblies);
container.SetFilterProvider(config.Services);
InsertRegisterRequestMessageHandler(config);
config.DependencyResolver = new DryIocDependencyResolver(container, throwIfUnresolved);
return container;
}
In the first syntax example, you create a new instance of Container and pass that newly created instance to .WithWebApi(). This in turn updates the container instance and finally returns it back to variable c.
In the second syntax example, you are never returning the value of the extension method BACK to the original variable, updating it. You are calling it as if it were a void method, which does nothing in this case, hence the exception.
If you had instead written:
var c = new Container();
c = c.WithWebApi(config);
it would have essentially been a more verbose example of the first syntax and would have properly updated c with the new functionality.
This seems fine and should work. Obviously the container returned from ccontainer.WithWebApi(config); is not the original container, which is unexpected at this point and therefore at least a code smell, since it gives rise to possible bugs. Better write a couple of unit tests and open an issue at the DryIoC Bitbucket site.
To help you out, here is an template of how to write such tests. Create a new test project and do the following:
Install NuGet Packages
Install-Package Microsoft.AspNet.WebApi.OwinSelfHost
Install-Package DryIoc.WebApi.Owin.dll
Install-Package Xunit
Controller
public sealed class ValuesController : ApiController
{
private IWidgetService WidgetService { get; }
public ValuesController(IWidgetService widgetService)
{
if(widgetService == null)
throw new ArgumentNullException(nameof(widgetService));
WidgetService = widgetService;
}
[HttpGet]
public IEnumerable<Widget> Get()
{
return WidgetService.GetWidgets().ToArray();
}
}
OWIN Startup
public sealed class Startup
{
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration()
.ConfigureRouting()
.ConfigureDependencyInjection();
app.UseWebApi(config);
// protip: use OWIN error page instead of ASP.NET yellow pages for better diagnostics
// Install-Package Microsoft.Owin.Diagnostics
// app.UseErrorPage(ErrorPageOptions.ShowAll);
}
private static HttpConfiguration ConfigureRouting(this HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "default",
routeTemplate: "/",
defaults: new { controller = "values" });
return config;
}
private static HttpConfiguration ConfigureDependencyInjection(this HttpConfiguration config)
{
new Container()
.Register<IWidgetService, WidgetService>(Reuse.Singleton)
.Register<IWidgetRepository, WidgetRepository>(Reuse.Singleton)
.WithWebApi(config);
return config;
}
}
Unit Test
[Fact]
public async Task ShouldFoo()
{
const string baseAddress = "http://localhost:8000";
using (WebApp.Start<Startup>(baseAddress))
{
var httpclient = new HttpClient
{
BaseAddress = new Uri(baseAddress)
};
var response = await httpclient.GetAsync("/");
Assert.That(...);
}
}
I have followed the below sample and it works fine until I have replaced the ProductsContext class by my own LDAPConnector class that need to get data from AD and since it's not working and get the Parameterless error.
http://www.asp.net/web-api/overview/advanced/dependency-injection
What I should add in the webAPIConfig.cs in order to register this new class ?
I have try this but it's not working:
container.RegisterType<ILDAPConnector, LDAPConnector>(new HierarchicalLifetimeManager());
I have also tried to add parameterless construction in both Controller and in the LDAPConnector class but still get the same issue.
The controller
public class ADAccountController : ApiController
{
IADAccountRepository _repository;
public ADAccountController() : base()
{
}
public ADAccountController(IADAccountRepository repository)
{
_repository = repository;
}
public IHttpActionResult GetByID(string id)
{
try
{
if (!string.IsNullOrWhiteSpace(id))
{
AccountAD contact = _repository.GetByID(id);
if (contact == null)
{
return NotFound();
}
return Ok(contact);
the Repository where I get the error on the LDAPConnector connector = new LDAPConnector();
public class ADAccountRepository : IADAccountRepository
{
static ConcurrentDictionary<string, AccountAD> _todos = new ConcurrentDictionary<string, AccountAD>();
private LDAPConnector connector = new LDAPConnector();
public ADAccountRepository()
{
Add(new AccountAD { Name = "Item1" });
}
public AccountAD GetByID(string id)
{
return connector.GetAccountDetails(id);
//AccountAD item;
//_todos.TryGetValue(id, out item);
//return item;
}
The ADConnector
public class LDAPConnector : ILDAPConnector
{
public LDAPConnector ()
{
}
public AccountAD GetAccountDetails(string id)
{
AccountAD _AccountDetails = new AccountAD();
List<SearchResult> searchResult = new List<SearchResult>();
finally the webapiconfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var container = new UnityContainer();
container.RegisterType<IADAccountRepository, ADAccountRepository>(new HierarchicalLifetimeManager());
container.RegisterType<ILDAPConnector, LDAPConnector>(new HierarchicalLifetimeManager());
//container.RegisterType<LDAPConnector>(new InjectionFactory(c => new LDAPConnector()));
config.DependencyResolver = new UnityResolver(container);
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var appXmlType = config.Formatters.XmlFormatter.SupportedMediaTypes.FirstOrDefault(t => t.MediaType == "application/xml");
config.Formatters.XmlFormatter.SupportedMediaTypes.Remove(appXmlType);
}
}
error reported:
{"Message":"An error has occurred.","ExceptionMessage":"An error occurred when trying to create a controller of type 'ADAccountController'. Make sure that the controller has a parameterless public constructor.","ExceptionType":"System.InvalidOperationException","StackTrace":" at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)\r\n at System.Web.Http.Controllers.HttpControllerDescriptor.CreateController(HttpRequestMessage request)\r\n at System.Web.Http.Dispatcher.HttpControllerDispatcher.<SendAsync>d__1.MoveNext()","InnerException":{"Message":"An error has occurred.","ExceptionMessage":"Type 'ADConnector.Controllers.ADAccountController' does not have a default constructor","ExceptionType":"System.ArgumentException","StackTrace":" at System.Linq.Expressions.Expression.New(Type type)\r\n at System.Web.Http.Internal.TypeActivator.Create[TBase](Type instanceType)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.GetInstanceOrActivator(HttpRequestMessage request, Type controllerType, Func`1& activator)\r\n at System.Web.Http.Dispatcher.DefaultHttpControllerActivator.Create(HttpRequestMessage request, HttpControllerDescriptor controllerDescriptor, Type controllerType)"}}
Unity tries to pick the constructor with the most arguments, I think in this case the exception is misleading.
Not got IDE to hand, but does this work?
container.RegisterType<ILDAPConnector>(new HierarchicalLifetimeManager(),
new InjectionFactory(c => new LDAPConnector()));
I've been banging my head on trying to get ViewModels to validate with webapi 2.2
From the docs ..it should work:
http://www.asp.net/web-api/overview/formats-and-model-binding/model-validation-in-aspnet-web-api
namespace WebApplication3.Controllers
{
public class ValidateModelAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (actionContext.ModelState.IsValid == false)
{
actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
}
}
public class TestViewModel
{
[Required]
[EmailAddress]
[MinLength(3)]
[MaxLength(255)]
[DataType(DataType.EmailAddress)]
public string Email { get; set; }
}
public class ValuesController : ApiController
{
[ValidateModel]
[HttpGet]
public string Test(TestViewModel email)
{
if (ModelState.IsValid)
{
return "ok";
}
return "not ok";
}
}
}
With or without the ValidateModelAttribute it just returns "ok" all the time...
The ValidateModelAttribute is registered in WebApiConfig
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
config.Filters.Add(new ValidateModelAttribute());
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
Anyone have an idea whats going on here ? It's so much simpler to use DataAnnotations to prevalidate data.
Sample request:
http://localhost:55788/api/values/Test?email=ss
Returns: ok
Neither GET/POST changes anything
Where simple MVC controllers seem to have no problem, in this web api example we apparently have to specify [FromUri]
This works just fine
[HttpGet]
public string Test([FromUri]TestViewModel email)
{
if (ModelState.IsValid)
{
return "ok";
}
return "not ok";
}
With this code i can now also implement jsonP behavior
Also the custom ValidateModelAttribute becomes obsolete, though it can still be useful if you want to throw an exception systematically when a ViewModel is invalid. I rather just handle it in code to be able to return custom error objects.
Before adding OData to my project, my routes where set up like this:
config.Routes.MapHttpRoute(
name: "ApiById",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = #"^[0-9]+$" },
handler: sessionHandler
);
config.Routes.MapHttpRoute(
name: "ApiByAction",
routeTemplate: "api/{controller}/{action}",
defaults: new { action = "Get" },
constraints: null,
handler: sessionHandler
);
config.Routes.MapHttpRoute(
name: "ApiByIdAction",
routeTemplate: "api/{controller}/{id}/{action}",
defaults: new { id = RouteParameter.Optional },
constraints: new { id = #"^[0-9]+$" },
handler: sessionHandler
All controllers provide Get, Put (action name is Create), Patch (action name is Update) and Delete. As an example, the client uses these various standard url's for the CustomerType requests:
string getUrl = "api/CustomerType/{0}";
string findUrl = "api/CustomerType/Find?param={0}";
string createUrl = "api/CustomerType/Create";
string updateUrl = "api/CustomerType/Update";
string deleteUrl = "api/CustomerType/{0}/Delete";
Then I added an OData controller with the same action names as my other Api controllers. I also added a new route:
ODataConfig odataConfig = new ODataConfig();
config.MapODataServiceRoute(
routeName: "ODataRoute",
routePrefix: null,
model: odataConfig.GetEdmModel()
);
So far I changed nothing on the client side. When I send a request, I get a 406 Not Available error.
Are the routes getting mixed up? How can I solve this?
If you are using OData V4, replace using System.Web.Http.OData;
With using Microsoft.AspNet.OData; (Please check the comments for the latest library)
in the ODataController works for me.
The order in which the routes are configured has an impact. In my case, I also have some standard MVC controllers and help pages. So in Global.asax:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(config =>
{
ODataConfig.Register(config); //this has to be before WebApi
WebApiConfig.Register(config);
});
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
}
The filter and routeTable parts weren't there when I started my project and are needed.
ODataConfig.cs:
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes(); //This has to be called before the following OData mapping, so also before WebApi mapping
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<Site>("Sites");
//Moar!
config.MapODataServiceRoute("ODataRoute", "api", builder.GetEdmModel());
}
WebApiConfig.cs:
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute( //MapHTTPRoute for controllers inheriting ApiController
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
And as a bonus, here's my RouteConfig.cs:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute( //MapRoute for controllers inheriting from standard Controller
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
);
}
This has to be in that EXACT ORDER. I tried moving the calls around and ended up with either MVC, Api or Odata broken with 404 or 406 errors.
So I can call:
localhost:xxx/ -> leads to help pages (home controller, index page)
localhost:xxx/api/ -> leads to the OData $metadata
localhost:xxx/api/Sites -> leads to the Get method of my SitesController inheriting from ODataController
localhost:xxx/api/Test -> leads to the Get method of my TestController inheriting from ApiController.
Set routePrefix to "api".
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
builder.EntitySet<CustomerType>("CustomerType");
config.MapODataServiceRoute(routeName: "ODataRoute", routePrefix: "api", model: builder.GetEdmModel());
Which OData version are you using? Check for correct namespaces, for OData V4 use System.Web.OData, for V3 System.Web.Http.OData. Namespaces used in controllers have to be consistent with the ones used in WebApiConfig.
My issue was related to returning the entity model instead of the model I exposed (builder.EntitySet<ProductModel>("Products");). Solution was to map entity to resource model.
Another thing to be taken into consideration is that the URL is case sensitive so:
localhost:xxx/api/Sites -> OK
localhost:xxx/api/sites -> HTTP 406
The problem I had was that i had named my entityset "Products" and had a ProductController. Turns out the name of the entity set must match your controller name.
So
builder.EntitySet<Product>("Products");
with a controller named ProductController will give errors.
/api/Product will give a 406
/api/Products will give a 404
So using some of the new C# 6 features we can do this instead:
builder.EntitySet<Product>(nameof(ProductsController).Replace("Controller", string.Empty));
None of the excellent solutions on this page worked for me. By debugging, I could see that the route was getting picked up and the OData queries were running correctly. However, they were getting mangled after the controller had exited, which suggested that it was the formatting that was generating what appears to be the OData catch-all error: 406 Not Acceptable.
I fixed this by adding a custom formatter based on the Json.NET library:
public class JsonDotNetFormatter : MediaTypeFormatter
{
public JsonDotNetFormatter()
{
SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/json"));
}
public override bool CanReadType(Type type)
{
return true;
}
public override bool CanWriteType(Type type)
{
return true;
}
public override async Task<object> ReadFromStreamAsync(Type type, Stream readStream, HttpContent content, IFormatterLogger formatterLogger)
{
using (var reader = new StreamReader(readStream))
{
return JsonConvert.DeserializeObject(await reader.ReadToEndAsync(), type);
}
}
public override async Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
if (value == null) return;
using (var writer = new StreamWriter(writeStream))
{
await writer.WriteAsync(JsonConvert.SerializeObject(value, new JsonSerializerSettings {ReferenceLoopHandling = ReferenceLoopHandling.Ignore}));
}
}
Then in WebApiConfig.cs, I added the line config.Formatters.Insert(0, new JsonDotNetFormatter()). Note that I am sticking closely to the order described in Jerther's answer.
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
ConfigureODataRoutes(config);
ConfigureWebApiRoutes(config);
}
private static void ConfigureWebApiRoutes(HttpConfiguration config)
{
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new { id = RouteParameter.Optional });
}
private static void ConfigureODataRoutes(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Formatters.Insert(0, new JsonDotNetFormatter());
var builder = new ODataConventionModelBuilder();
builder.EntitySet<...>("<myendpoint>");
...
config.MapODataServiceRoute("ODataRoute", "odata", builder.GetEdmModel());
}
}
The problem/solution in my case was even more stupid. I'd left test code in my action that returned a completely different model type, just a Dictionary, and not my proper EDM model type.
Though I protest that the use of HTTP 406 Not Acceptable to communicate the error of my ways, is equally as stupid.
My error and fix was different from the answers above.
The specific issue I had was accessing a mediaReadLink endpoint in my ODataController in WebApi 2.2.
OData has a 'default stream' property in the spec which allows a returned entity to have an attachment. So the e.g. json object for filter etc describes the object, and then there is a media link embedded which can also be accessed. In my case it is a PDF version of the object being described.
There's a few curly issues here, the first comes from the config:
<system.web>
<customErrors mode="Off" />
<compilation debug="true" targetFramework="4.7.1" />
<httpRuntime targetFramework="4.5" />
<!-- etc -->
</system.web>
At first I was trying to return a FileStreamResult, but i believe this isn't the default net45 runtime. so the pipeline can't format it as a response, and a 406 not acceptable ensues.
The fix here was to return a HttpResponseMessage and build the content manually:
[System.Web.Http.HttpGet]
[System.Web.Http.Route("myobjdownload")]
public HttpResponseMessage DownloadMyObj(string id)
{
try
{
var myObj = GetMyObj(id); // however you do this
if (null != myObj )
{
HttpResponseMessage result = Request.CreateResponse(HttpStatusCode.OK);
byte[] bytes = GetMyObjBytes(id); // however you do this
result.Content = new StreamContent(bytes);
result.Content.Headers.ContentType = new MediaTypeWithQualityHeaderValue("application/pdf");
result.Content.Headers.LastModified = DateTimeOffset.Now;
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue(DispositionTypeNames.Attachment)
{
FileName = string.Format("{0}.pdf", id),
Size = bytes.length,
CreationDate = DateTimeOffset.Now,
ModificationDate = DateTimeOffset.Now
};
return result;
}
}
catch (Exception e)
{
// log, throw
}
return null;
}
My last issue here was getting an unexpected 500 error after returning a valid result. After adding a general exception filter I found the error was Queries can not be applied to a response content of type 'System.Net.Http.StreamContent'. The response content must be an ObjectContent.. The fix here was to remove the [EnableQuery] attribute from the top of the controller declaration, and only apply it at the action level for the endpoints that were returning entity objects.
The [System.Web.Http.Route("myobjdownload")] attribute is how to embed and use media links in OData V4 using web api 2.2. I'll dump the full setup of this below for completeness.
Firstly, in my Startup.cs:
[assembly: OwinStartup(typeof(MyAPI.Startup))]
namespace MyAPI
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
// DI etc
// ...
GlobalConfiguration.Configure(ODataConfig.Register); // 1st
GlobalConfiguration.Configure(WebApiConfig.Register); // 2nd
// ... filters, routes, bundles etc
GlobalConfiguration.Configuration.EnsureInitialized();
}
}
}
ODataConfig.cs:
// your ns above
public static class ODataConfig
{
public static void Register(HttpConfiguration config)
{
ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
var entity1 = builder.EntitySet<MyObj>("myobj");
entity1.EntityType.HasKey(x => x.Id);
// etc
var model = builder.GetEdmModel();
// tell odata that this entity object has a stream attached
var entityType1 = model.FindDeclaredType(typeof(MyObj).FullName);
model.SetHasDefaultStream(entityType1 as IEdmEntityType, hasStream: true);
// etc
config.Formatters.InsertRange(
0,
ODataMediaTypeFormatters.Create(
new MySerializerProvider(),
new DefaultODataDeserializerProvider()
)
);
config.Select().Expand().Filter().OrderBy().MaxTop(null).Count();
// note: this calls config.MapHttpAttributeRoutes internally
config.Routes.MapODataServiceRoute("ODataRoute", "data", model);
// in my case, i want a json-only api - ymmv
config.Formatters.JsonFormatter.SupportedMediaTypes.Add(new MediaTypeWithQualityHeaderValue("text/html"));
config.Formatters.Remove(config.Formatters.XmlFormatter);
}
}
WebApiConfig.cs:
// your ns above
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// https://stackoverflow.com/questions/41697934/catch-all-exception-in-asp-net-mvc-web-api
//config.Filters.Add(new ExceptionFilter());
// ymmv
var cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);
// so web api controllers still work
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
// this is the stream endpoint route for odata
config.Routes.MapHttpRoute("myobjdownload", "data/myobj/{id}/content", new { controller = "MyObj", action = "DownloadMyObj" }, null);
// etc MyObj2
}
}
MySerializerProvider.cs:
public class MySerializerProvider: DefaultODataSerializerProvider
{
private readonly Dictionary<string, ODataEdmTypeSerializer> _EntitySerializers;
public SerializerProvider()
{
_EntitySerializers = new Dictionary<string, ODataEdmTypeSerializer>();
_EntitySerializers[typeof(MyObj).FullName] = new MyObjEntitySerializer(this);
//etc
}
public override ODataEdmTypeSerializer GetEdmTypeSerializer(IEdmTypeReference edmType)
{
if (edmType.IsEntity())
{
string stripped_type = StripEdmTypeString(edmType.ToString());
if (_EntitySerializers.ContainsKey(stripped_type))
{
return _EntitySerializers[stripped_type];
}
}
return base.GetEdmTypeSerializer(edmType);
}
private static string StripEdmTypeString(string t)
{
string result = t;
try
{
result = t.Substring(t.IndexOf('[') + 1).Split(' ')[0];
}
catch (Exception e)
{
//
}
return result;
}
}
MyObjEntitySerializer.cs:
public class MyObjEntitySerializer : DefaultStreamAwareEntityTypeSerializer<MyObj>
{
public MyObjEntitySerializer(ODataSerializerProvider serializerProvider) : base(serializerProvider)
{
}
public override Uri BuildLinkForStreamProperty(MyObj entity, EntityInstanceContext context)
{
var url = new UrlHelper(context.Request);
string id = string.Format("?id={0}", entity.Id);
var routeParams = new { id }; // add other params here
return new Uri(url.Link("myobjdownload", routeParams), UriKind.Absolute);
}
public override string ContentType
{
get { return "application/pdf"; }
}
}
DefaultStreamAwareEntityTypeSerializer.cs:
public abstract class DefaultStreamAwareEntityTypeSerializer<T> : ODataEntityTypeSerializer where T : class
{
protected DefaultStreamAwareEntityTypeSerializer(ODataSerializerProvider serializerProvider)
: base(serializerProvider)
{
}
public override ODataEntry CreateEntry(SelectExpandNode selectExpandNode, EntityInstanceContext entityInstanceContext)
{
var entry = base.CreateEntry(selectExpandNode, entityInstanceContext);
var instance = entityInstanceContext.EntityInstance as T;
if (instance != null)
{
entry.MediaResource = new ODataStreamReferenceValue
{
ContentType = ContentType,
ReadLink = BuildLinkForStreamProperty(instance, entityInstanceContext)
};
}
return entry;
}
public virtual string ContentType
{
get { return "application/octet-stream"; }
}
public abstract Uri BuildLinkForStreamProperty(T entity, EntityInstanceContext entityInstanceContext);
}
The end result is my json objects get these odata properties embedded:
odata.mediaContentType=application/pdf
odata.mediaReadLink=http://myhost/data/myobj/%3fid%3dmyid/content
And the following the decoded media link http://myhost/data/myobj/?id=myid/content fires the endpoint on your MyObjController : ODataController.
Found in the GitHub error: "Unable to use odata $select, $expand, and others by default #511", their solution is to put the following line BEFORE registering the route:
// enable query options for all properties
config.Filter().Expand().Select().OrderBy().MaxTop(null).Count();
Worked like a charm for me.
Source: https://github.com/OData/RESTier/issues/511
In my case I needed to change a non-public property setter to public.
public string PersonHairColorText { get; internal set; }
Needed to be changed to:
public string PersonHairColorText { get; set; }
In my case (odata V3) I had to change name of OdataController to be same as provided in
ODataConventionModelBuilder and that solved the issue
my controller:
public class RolesController : ODataController
{
private AngularCRMDBEntities db = new AngularCRMDBEntities();
[Queryable]
public IQueryable<tROLE> GetRoles()
{
return db.tROLEs;
}
}
ODataConfig.cs:
public class ODataConfig
{
public static void Register(HttpConfiguration config)
{
ODataConventionModelBuilder modelBuilder = new ODataConventionModelBuilder();
modelBuilder.EntitySet<WMRole>("RolesNormal");
modelBuilder.EntitySet<WMCommon.DAL.EF.tROLE>("Roles").EntityType.HasKey(o => o.IDRole).HasMany(t => t.tROLE_AUTHORIZATION);
modelBuilder.EntitySet<WMCommon.DAL.EF.tLOOKUP>("Lookups").EntityType.HasKey(o => o.IDLookup).HasMany(t => t.tROLE_AUTHORIZATION);
modelBuilder.EntitySet<WMCommon.DAL.EF.tROLE_AUTHORIZATION>("RoleAuthorizations").EntityType.HasKey(o => o.IDRoleAuthorization);
config.Routes.MapODataRoute("odata", "odata", modelBuilder.GetEdmModel());
config.EnableQuerySupport();
}
}
WebApiConfig.cs:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
config.Routes.MapHttpRoute( //MapHTTPRoute for controllers inheriting ApiController
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
var jsonFormatter = config.Formatters.OfType<JsonMediaTypeFormatter>().First();
jsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
}
}
Global.asax:
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(config =>
{
ODataConfig.Register(config);
WebApiConfig.Register(config);
});
}
}
For me the problem was, that I used LINQ and selected the loaded objects directly.
I had to use select new for it to work:
return Ok(from u in db.Users
where u.UserId == key
select new User
{
UserId = u.UserId,
Name = u.Name
});
This did not work:
return Ok(from u in db.Users
where u.UserId == key
select u);