How to implement Unity Container DI in Azure Function v2 - c#

Earlier in WebAPI, I used to implement Unity container Dependency Injection as below
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
//I want to implement below in Azure Function V2
var container = new UnityContainer();
container.RegisterType<IDeviceRepository, DeviceRepository>(new HierarchicalLifetimeManager());
container.RegisterType<IFilterRepository, FilterRepository>(new HierarchicalLifetimeManager());
container.RegisterType<INEORepository, NEORepository>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
}
}
How can I implement above code in Azure Function V2.
I had gone through few online articles but didn't get proper solution.
Kindly suggest.

I have used below code to implement DI in Azure functions.
public class GenericDependencyInjection
{
private static readonly UnityContainer UnityContainer = new UnityContainer();
public GenericDependencyInjection()
{
try
{
UnityContainer.RegisterType<IOperations,Operations>(new ContainerControlledLifetimeManager());
}
catch (Exception ex)
{
throw ;
}
}
public T Retrieve<T>()
{
return UnityContainer.Resolve<T>();
}
}
I have called Retrieve method by passing generic type as below in other classes
var data = new GenericDependencyInjection().Retrieve<EmpDetails>();
return await data.UpdateDetails(EmpId, Name); //calling class EmpDetails method

Related

Dependency Injection in .Net Framework using Microsoft.Owin and WebApi Routing

I am trying to build basic Webapi using Microsoft.Owin on Console Application. Everything works well until Dependency Injection.
In this code, Owin and Webapi routing works well
private static void RunWebApi()
{
const string baseAddress = "http://localhost:5000/";
WebApp.Start<Startup>(url: baseAddress);
}
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "1",
routeTemplate: "api/{controller}/{action}/{value}",
defaults: new { value = RouteParameter.Optional }
);
appBuilder.UseWebApi(config);
}
}
public interface ISingletonService
{
string Id { get; }
}
public class SingletonService : ISingletonService
{
public string Id { get; } = Guid.NewGuid().ToString();
}
public class SettingsController: ApiController
{
public SingletonService manager;
public SettingsController(SingletonService manager)
{
this.manager = manager;
}
public SettingsController(){}
[HttpPost]
public HttpResponseMessage StartDeviceManager()
{
var response = Request.CreateResponse(HttpStatusCode.Accepted, "value");
response.Content = new StringContent("Hello", Encoding.Unicode);
response.Headers.CacheControl = new CacheControlHeaderValue()
{
MaxAge = TimeSpan.FromMinutes(20)
};
return response;
}
}
I added this https://github.com/AxaGuilDEv/extensions-dependency-injection package to project and try to use it.
Implementation code:
public class Startup
{
public void Configuration(IAppBuilder appBuilder)
{
var config = new HttpConfiguration();
config.MapHttpAttributeRoutes();
config.DependencyResolver = new DefaultDependencyResolver(ServiceProviderConfig.ServiceProvider);
config.Routes.MapHttpRoute(
name: "1",
routeTemplate: "api/{controller}/{action}",
defaults: null
);
ServiceCollection services = new ServiceCollection();
services.AddSingleton<ISingletonService, SingletonService>();
appBuilder.UseScopedServiceProvider(services.BuildServiceProvider());
appBuilder.Use((context, next) =>
{
var serviceScope = context.GetDependencyScope();
var singletonService = serviceScope.ServiceProvider.GetService<ISingletonService>();
string message = $"singleton ID : {singletonService.Id}";
context.Response.WriteAsync(message);
return Task.FromResult(0);
});
}
}
At this point, Dependency Injection works well but routing has no effect, I tried to add appBuilder.UseWebApi(config), but no response on any route.
Is there any way to use both of them in Microsoft.Owin(Katana)?
I am trying to build web api on .net framework Console Application. Routing and Dependency Injection does not working at same time. I am trying to solve this problem.

Async Callback threw an exception

I am getting the following error when trying to NServiceBus with autofac DI:
InvalidOperationException: The IAsyncResult implementation 'Microsoft.ServiceBus.Messaging.Channels.ReconnectBindingElement+ReconnectChannelFactory`1+RequestSessionChannel+RequestAsyncResult[System.ServiceModel.Channels.IRequestSessionChannel]' tried to complete a single operation multiple times. This could be caused by an incorrect application of IAsyncResult implementation or other extensibility code, such as an IAsyncResult that returns incorrect CompletedSynchronously values, or invokes the AsyncCallback multiple times.
WebApiConfig:
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
try
{
var builder = new ContainerBuilder();
builder.RegisterApiControllers(Assembly.GetExecutingAssembly()).PropertiesAutowired();
builder.RegisterType<MessageHandler>().As<IMessageHandler>().InstancePerLifetimeScope();
var container = builder.Build();
var bus = CreateBusInstance(container);
builder.RegisterInstance(bus).As<IBus>().SingleInstance();
var resolver = new AutofacWebApiDependencyResolver(container);
config.DependencyResolver = resolver;
}
catch(Exception e)
{
throw;
}
}
private static IBus CreateBusInstance(ILifetimeScope container)
{
var configuration = new BusConfiguration();
configuration.EndpointName("ServiceBusName");
configuration.DisableFeature<SecondLevelRetries>();
configuration.DisableFeature<Sagas>();
configuration.DisableFeature<TimeoutManager>();
configuration.ScaleOut().UseSingleBrokerQueue();
configuration.UsePersistence<AzureStoragePersistence>();
configuration.UseTransport<AzureServiceBusTransport>().ConnectionString(ConfigurationManager.ConnectionStrings["ServiceBus"].ToString());
configuration.UseSerialization<XmlSerializer>();
configuration.UseContainer<AutofacBuilder>(cust => cust.ExistingLifetimeScope(container));
return Bus.Create(configuration).Start();
}
}
MessageHandler:
using nservciebus.Models;
using NServiceBus;
namespace nservciebus.ServiceBusHandler
{
public class MessageHandler : IMessageHandler
{
private readonly IBus _bus;
public MessageHandler(IBus bus)
{
_bus = bus;
}
public void Handle(ServiceBusMessage message)
{
_bus.Send(message);
}
}
}
Nuget package in use:
- Autofac: 3.5.2
- Autofac.Owin: 4.0
- Autofac.WebApi2: 4.0
- Autofac.WebApi2.Owin: 4.0
- NServiceBus: 5.2.14
- NServiceBus.Autofac: 5.0
- NServiceBus.Azure.transports.WindowsAzureServiceBus: 6.4
- NServiceBus.Azure: 6.2.3
- WindowsAzure.Storage: 4.3
- WindowsAzure.ServiceBus: 2.8.2
AnyIdeas on what is causing this problem and how to fix it?
Thanks

An error occurred when trying to create a controller of type 'SaleController'. Make sure that the controller has a parameterless public constructor

I have been following this article:
https://learn.microsoft.com/en-us/aspnet/web-api/overview/advanced/dependency-injection#dependency-scope-and-controller-lifetime
The error I get is in the title:
Make sure that the controller has a parameterless public constructor.
Basically the Unity code is the same as in the project from microsoft.
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
var container = new UnityContainer();
container.RegisterType<ITrace, Trace>(new HierarchicalLifetimeManager());
container.RegisterType<IUtility, Utility>(new HierarchicalLifetimeManager());
container.RegisterType<IValidator, Validator>(new HierarchicalLifetimeManager());
container.RegisterType<IDeliveryService, DeliveryService>(new HierarchicalLifetimeManager());
container.RegisterType<ISaleService, SaleService>(new HierarchicalLifetimeManager());
config.DependencyResolver = new UnityResolver(container);
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
I have UnityResolver:
public class UnityResolver : IDependencyResolver
{
protected IUnityContainer container;
public UnityResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public object GetService(Type serviceType)
{
try
{
return container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return container.ResolveAll(serviceType);
}
catch (ResolutionFailedException)
{
return new List<object>();
}
}
public IDependencyScope BeginScope()
{
var child = container.CreateChildContainer();
return new UnityResolver(child);
}
public void Dispose()
{
container.Dispose();
}
Unity should instantiate the controllers using this. My only concern is the db context. I tried searching for ways to register but I got nothing.
As asked here is my dbcontext:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext() : base("DefaultConnection", throwIfV1Schema: false)
{
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
Configuration.ValidateOnSaveEnabled = false;
}
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
I am using Unity for the first time.
In Unity sometimes custom classes that have a specific constructor also require an additional parameter-less constructor (It may be doing nothing but has to exist) like
public UnityResolver(){ }
Afaik this is mostly related to (de)serialization. Not sure why it is required in our specific case .. but that is what the error tries to tell you ;)

Api Controller has a parameterless public constructor error

I am using Unity to do my DI and I have encountered the following error:-
"An error occurred when trying to create a controller of type 'UploadController'. Make sure that the controller has a parameterless public constructor."
I have the following UnityResolver:-
public class UnityResolver : IDependencyResolver, IDependencyScope, System.Web.Http.Dependencies.IDependencyResolver
{
protected IUnityContainer container;
public UnityResolver(IUnityContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
this.container = container;
}
public object GetService(Type serviceType)
{
try
{
return container.Resolve(serviceType);
}
catch (ResolutionFailedException)
{
return null;
}
}
public IEnumerable<object> GetServices(Type serviceType)
{
try
{
return container.ResolveAll(serviceType);
}
catch (ResolutionFailedException)
{
return new List<object>();
}
}
public IDependencyScope BeginScope()
{
var child = container.CreateChildContainer();
return new UnityResolver(child);
}
public void Dispose()
{
container.Dispose();
}
}
}
I have created a UnityConfig as follows:-
public static class UnityConfig
{
public static void RegisterComponents()
{
var container = new UnityContainer();
// register all your components with the container here
// it is NOT necessary to register your controllers
// e.g. container.RegisterType<ITestService, TestService>();
BuildUnityContainer();
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
}
private static IUnityContainer BuildUnityContainer()
{
var container = new UnityContainer();
// register all your components with the container here
// you don't need to register controllers
container.RegisterType<IFileHelpers, FileHelpers>();
container.RegisterType<IDatabaseHelper, DatabaseHelper>();
container.RegisterType<IPlayersHelpers, PlayersHelpers>();
container.RegisterType<IBaseRepository, BaseRepository>();
container.RegisterType<IAttribsRepository, AttribsRepository>();
container.RegisterType<IPlayerRepository, PlayerRepository>();
container.RegisterType<IFileRepository, FileRepository>();
container.RegisterType<IPlayerAttribsRepository, PlayerAttribsRepository>();
container.RegisterType<FMContext>();
container.RegisterType<UserManager<ApplicationUser>>(new HierarchicalLifetimeManager());
container.RegisterType<IUserStore<ApplicationUser>, UserStore<ApplicationUser>>(new HierarchicalLifetimeManager());
return container;
}
}
}
Im initializing everyting in the WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
// Web API configuration and services
// Configure Web API to use only bearer token authentication.
config.SuppressDefaultHostAuthentication();
config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));
// Web API configuration and services
var container = new UnityContainer();
UnityConfig.RegisterComponents();
config.DependencyResolver = new UnityResolver(container);
config.EnableCors();
// Web API routes
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
And this is my UploadController class:-
public class UploadController : ApiController
{
private readonly IFileHelpers _fileHelpers;
private readonly IDatabaseHelper _databaseHelper;
private readonly IPlayersHelpers _playersHelpers;
public UploadController(IFileHelpers fileHelpers, IDatabaseHelper databaseHelper, IPlayersHelpers playersHelpers)
{
_fileHelpers = fileHelpers;
_databaseHelper = databaseHelper;
_playersHelpers = playersHelpers;
}
public async Task<HttpResponseMessage> Post()
{........................}
Can you please help me in determining what am I doing wrong. Do I need to declare something else for this to work?
Thanks for your help and time
In your Register method, you have the following code:
// ...
// Web API configuration and services
var container = new UnityContainer();
UnityConfig.RegisterComponents();
config.DependencyResolver = new UnityResolver(container);
However, there is nothing registered to that container. There is a separate container (with registrations) being created in your static UnityConfig class, but that container is not being passed to the UnityResolver object...

WebAPI and ODataController return 406 Not Acceptable

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);

Categories

Resources