asp.net-web-api,filter,dependency-injection,authorization,autofac , Is there a way to use AutoFac Web Api Authorization Filters through Attributes instead of injection?


Is there a way to use AutoFac Web Api Authorization Filters through Attributes instead of injection?

Question:

Tag: asp.net-web-api,filter,dependency-injection,authorization,autofac

I have an Autofac Web Api Authorization Filter like that:

public class MyAuthorizationFilter : IAutofacAuthorizationFilter
{
    public void OnAuthorization(HttpActionContext actionContext){}
}

public class MyAuthorizationAttribute : Attribute
{
    public MyAuthorizationAttribute() { }
}

Right now the only way I can have an Autofac Web Api Authorization Filter is through injecting it in AutofacConfig.cs:

builder.RegisterType<MyAuthorizationFilter>()
.AsWebApiAuthorizationFilterFor<MyController>(
    c => c.MyMethod(default(MyModel))
).InstancePerDependency();

and it seems the attribute is ignored if I don't inject it as above

public MyController : ApiController {

    [MyAuthroziationFilter] // ignored
    [POST("")]
    public HttpResponseMessage MyMethod(MyModel myModel) { 
        [...]
    }
}

Is there a way to use attributes/annotations for AutoFac Web Api Authorization Filters instead of injections through AutoFac and also have their dependencies properly injected?


Answer:

Unfortunately, if you want DI in your filters, you can't use attributes. Per the docs:

Unlike the filter provider in MVC, the one in Web API does not allow you to specify that the filter instances should not be cached. This means that all filter attributes in Web API are effectively singleton instances that exist for the entire lifetime of the application.

If you want to use attributes, the best you can do is use service location inside standard Web API attributes. Get the request lifetime scope off the request message and manually resolve the services you need.


Related:


OnAuthorization Method of AuthorizationFilterAttribute will execute every time when request arrives?


c#,asp.net-web-api
I am writing Web API ( v2.2 ) for accessing another REST API. Reason is that I want restrict some functional and provide more friendly data. In short I am writing wrapper for some REST API. I am providing authentication/authorization via my Implementation of AuthorizationFilterAttribute. Here is snippet of code:...

How do I do to count rows in a sheets with filters? With a suppress lines


excel,vba,filter
I have a sheet with lots of columns, but when I filter and use count = Application.WorksheetFunction.CountA(Range("A:A")) It returns all the rows non Empty. Not only the rows I filtered....

Passing complex array from Controller to View ASP.NET MVC


c#,asp.net,asp.net-mvc,asp.net-web-api
I have a model in my ASP.NET MVC application: public class SearchArrayModel { public long ID { get; set; } public string Name { get; set; } public struct AttribStruct { public string AttribName { get; set; } public string[] AttribValues { get; set; } } public AttribStruct[] AttribStructTable {...

No 'Access-Control-Allow-Origin' header on one site, but not on another


c#,jquery,ajax,asp.net-web-api,cors
We have a system made up of a website, written in ASP.NET/MVC, and a webservices site, written in ASP.NET/WEBAPI. The user loads pages from the website, which make AJAX calls into the webservices site, using JQuery. We're building this with VS2013, and deploying it with MS's Web Deploy, run from...

Is it nessesarry to send credentials on every single request to MVC Web Api?


authentication,asp.net-web-api,web-api
I am about to create my first restfull web service where i chose MVC WEB API to be the "provider". After reading about authentication i am a little confused. My requirements is that on call to any url of webservice i want client to be authenticated, except sign in url....

Exclude underlying objects when storing data using EF6


asp.net,entity-framework,asp.net-web-api
I have a class Ticket which has some properties. Three of these (View, Task and Key) properties are navigation properties. Those properties already exist in database even before a ticket has been stored. In my application I load those properties from the database first and then create a Ticket object....

Manually validate Model in Web api controller


asp.net,asp.net-mvc,asp.net-web-api
I have a class called 'User' and a property 'Name' public class User { [Required] public string Name { get; set; } } And api controller method is public IHttpActionResult PostUser() { User u = new User(); u.Name = null; if (!ModelState.IsValid) return BadRequest(ModelState); return Ok(u); } How do i...

DOORS Compound Filter Dilemma


filter,dxl,doors
DOORS Version: 9.5.2.1 I'll try to break this down as simple as I can. First, I'll start with the data. Assume I have a module, Module, in DOORS. Module is comprised of: Tree Structure Assume that Object Text for headings and sub-headings are blank, and assume Object Text for the...

Excel VBA - ShowAllData fail - Need to know if there is a filter


excel,vba,excel-vba,filter
I have automated a proper record input into the table that I use as a database, and when the table is filtered the input don't work. So I have code this to unfilter DataBase before every record input. Public Sub UnFilter_DB() Dim ActiveS As String, CurrScreenUpdate As Boolean CurrScreenUpdate =...

WebApi Put how to tell not specified properties from specified properties set to null?


c#,.net,json,asp.net-web-api
Here is the scenario. There is an web api put call to change an object in sql server database. We want only to change the fields on the database object if they were explicitly specified on webapi call json. For example: { "Name":"newName", "Colour":null } That should change the Name...

How to setup Request.Header in FakeHttpContext for Unit Testing


c#,unit-testing,asp.net-web-api,httpcontext
I have a FakeHttpContext I have been trying to modify to include some headers for testing purposes public static HttpContext FakeHttpContext() { var httpRequest = new HttpRequest("", "http://stackoverflow/", ""); var stringWriter = new StringWriter(); var httpResponse = new HttpResponse(stringWriter); var httpContext = new HttpContext(httpRequest, httpResponse); var sessionContainer = new HttpSessionStateContainer("id",...

AngularJS Filter two select inputs with values less than or equal to value


javascript,angularjs,select,filter,compare
I would like to setup two select inputs so that the combined value of either select input should be less than or equal to a specific value. Newbie to the AngularJS world so I may have overlooked something. I assume a filter but it might be ng-change that I should...

Enforce ordering of OData items even when $top is used


linq,entity-framework,asp.net-web-api,odata,iqueryable
I have a DbSet<Items> collection. The primary key is a Guid. I don't want to order by this primary key. I want to order by an editable decimal property named "Order". The code I have is very simple, and it works great until the user puts a "$top" parameter into...

Android listview filter without pressing search button issue


android,database,listview,filter
I have a ListView which work fine. Now I have put an EditText at the top of my ListView. What I want is that when a enters a letter "A", only the names starting with an "A" should appear in the list . I have try to do this but...

Php filter system


php,mysql,filter
I want to make a php filter system like this with 4 variables: echo"<form action='' method='GET' class='form-inline' role='form'>"; $query = "SELECT Naam FROM Soortmaaltijd"; //Alle soortmaaltijden ophalen $result= mysql_query($query) or die(mysql_error()); echo"<div class='row'>"; echo"<div class='form-group' >"; echo"<label for='soortmaaltijd'>Soort maaltijd</label></br>"; echo"<select name='Soortmaaltijd' class='form-control' id='soortmaaltijd'>"; echo"<option...

Using Python, I want to parse each file in one directory with format YY-MM-DD.CSV but ignore all others


python,regex,file,filter
I'm new to Python, so my example represents the mess one aggregates when all experiments so far have failed. #!/usr/bin/python import glob import os import re path = '/home2/SunnyDataBackup/currentGenerated/SBEAM/' files = '[1][0-9]-[0-1][0-9]-[0-3][0-9].CSV$' #if I use '*.CSV', it works but doesn't filter the files fullpath = os.path.join(path, files) print fullpath #fullpathC...

What's the best way to map objects into ember model from REST Web API?


json,rest,ember.js,asp.net-web-api,ember-data
The topic of this post is: my solution is too slow for a large query return. I have a Web Api serving REST results like below from a call to localhost:9090/api/invetories?id=1: [ { "inventory_id": "1", "film_id": "1", "store_id": "1", "last_update": "2/15/2006 5:09:17 AM" }, { "inventory_id": "2", "film_id": "1", "store_id":...

Web API AuthorizeAttribute does not return custom response


c#,asp.net-web-api,asp.net-mvc-5
How can I make IsAuthorized return my custom object while function returns false? In my WebAPI project I have a class like; public class CustomAuthorizeAttribute : AuthorizeAttribute { protected override bool IsAuthorized(System.Web.Http.Controllers.HttpActionContext actionContext) { StandardWebAPIResponse invalidUserResponse = new StandardWebAPIResponse() { code = (int) Constants.ErrorCodes.InvalidCredentials, data = "InvalidCredentials.", StatusCode = HttpStatusCode.Unauthorized...

Database error in web api


c#,sql,linq,asp.net-web-api,odata
I am trying to create an odata endpoint for a table valued function in sql database. I get the exception: The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported. I am sure with my code and unable to...

Web API Basic Auth inside an MVC app with Identity Auth


c#,authentication,asp.net-web-api,asp.net-mvc-5
So I have a C# MVC app using Identity for its authentication. I now have a need to expose a few things via Web API to some of my clients. Instead of building a separate app, project, deployment... I've simply added an API Controller to my existing project. To keep...

Where should I store WebAPI controllers inside ASP.NET-MVC 5 project?


asp.net-mvc,asp.net-web-api,odata
I have completed an ASP.NET-MVC5 application(website) where I have lot of MVC controllers: I would like to extent the functionality of my application by exposing WEB API with OData. For instance I would like to create another controller for Person model class, but this time it should be Web API...

angularjs filter an array with string values as integers in contoller


arrays,angularjs,filter
I'm using AngularJS filter to filter an array of objects inside a controller. These objects all have a quality that is a string. I want to be able to filter the array from largest to smallest. But I can't get it filter on value of the integer inside the string....

Asp.net Web API Routing by action name fix


asp.net-mvc,rest,asp.net-web-api,asp.net-routing
I found this article at asp.net Learn website. I use this article to help me to create an API method to search in the database by email and not id. However, if you take a look at the article, you will be able to help me fix my problem as...

Cannot read property 'client' of undefined using SignalR


asp.net-web-api,signalr,signalr-hub
I've been working all day on this with no luck. I have also tried (almost) every single SO question, but I didn't get it to work... I'm running web api with very simple SignalR push message and separately simple front end to show this push message. In my case the...

How can I handle exceptions in Web API 1.0 at my BaseAPIController


.net,asp.net-web-api
I am currently using Web API 1.0 and .NET 4.0 I need a function that can take care of the noise of catching and handling exceptions in my Base API so that I dont need to write that in every RESTful operation. public int Get(WelcomeTeamNotes note) { try { return...

Route parameter with slash “/” in URL


asp.net-web-api,routing,asp.net-web-api2,asp.net-web-api-routing,attributerouting
I know you can apply a wildcard in the route attribute to allow / such as date input for example: [Route("orders/{*orderdate}")] The problem with wildcard is only applicable to the last paramter in URI. How do I solve the issue if want to have the following URI: [Route("orders/{orderdate}/customers")] ? EDIT:...

Web Api 2 or Generic Handler to serve images?


c#,asp.net,asp.net-web-api
I want to create an image handler, but i am torn between using Web API 2 or just a normal Generic Handler (ashx) I have implemented both in the past, but which one is the most correct one. I found an old SO post LINK but is it still really...

how to update multiple data in entityframework through async web api


entity-framework,asp.net-web-api,async-await,web-api,asp.net-web-api2
I am using web api 2, and entity framework 6. I have created an async web api, which updates all the records at once. I am also using Autofac for dependency injection. My service interface is as follows : Task<Approval> TakeAction(int id, bool isApprove) void TakeAction(bool isApprove) These are my...

how to post objects from angular to a webapi controller


javascript,c#,angularjs,asp.net-web-api,http-post
I am creating a pdf using pdfsharp. I need to pass the chart legend data(name,color) to the pdfsharp controller. I am using a angular $http post, a ajax post would be fine as well. the error I am getting is Request...

Web API and MVC in the same project with Session States


c#,asp.net-mvc,asp.net-web-api,session-state
I'm been working around an ASP .Net MVC application that is going take log in requests from different sites with different configurations (so I cannot use the FormsAuthentication SSO way). The way I decided to resolve this was by creating temporal login request tokens, so each token could be used...

DataTables Warning: Requested unknown parameter 'pCodigo' for row 0


asp.net-web-api,datatables
I'm trying to populate a table on a button click, getting the data from an ASP.NET ApiController. I've tried with almost all solutions posted in SO to other similar issues but always get that error. Hope someone sees the problem. The html markup: <input type="button" ID="btnSearch" name="btnSearch" class="btn btn-success" value="Buscar"...

query multi-level entity with filter at the lowest level


c#,asp.net,asp.net-web-api,linq-to-entities
So I have 3 entity classes: public partial class Event { public Event() { Recurrences = new HashSet<Recurrence>(); } public int Id { get; set; } public ICollection<Recurrence> Recurrences { get; set; } } public partial class Recurrence { public Recurrence() { AspNetUsers = new HashSet<AspNetUser>(); } public int Id...

Filter array of objects with another array of objects


javascript,jquery,arrays,object,filter
This question is similar to this one Jquery filter array of object with loop but this time I need to do the filter with an array of objects. Exemple: I have an array of objects like this: myArray = [ { userid: "100", projectid: "10", rowid: "0" }, { userid:...

How to retrieve filtered data from json with double for loop


javascript,json,loops,for-loop,filter
So i have build up this json file (http://www.smartbustracking.be/json/data.json) and now i am able to retrieve data. but what i would like to achieve is to filter data based on id with a for loop. i am able to show one item of a specific id but not all the...

Paging in .NET Web API


c#,.net,asp.net-web-api,odata,paging
I have to do paging for an odata endpoint built using Entity Framework . I know I can do it using private ODataQuerySettings settings = new ODataQuerySettings(); settings.PageSize = myPageSize; // I keep this value in web.config of solution and options.ApplyTo(IQueryable, settings); But I am constrained not to use ApplyTo...

Excel VBA range after filtering xlCellTypeVisible


excel,vba,excel-vba,filter,range
What I want to accomplish: Open a workbook from a specific address, Filter the first column for value equal to 36 or 541 (I got this first part working), then check column 3 to see if a value of 2 exists and if it exists then filter out everything except...

Jquery Filter Out Radio Buttons ( .not( ) )


php,jquery,filter
I want to remove the radiobuttons from my multiple choice quiz so users can review their answers. I put all of the questions to be reviewed in a div called reviewQuestions var question = '#question' + zz; // zz is a variable that produces a number var someVariable = $(question).not("input[type=radio]").html();...

Web API translating input into random int


c#,post,asp.net-web-api,json.net
not sure whether the subject is the best description for this problem but I am getting an unusual problem where I have a single Web API operation and a single field on a request and for some odd reason the value gets manipulated. Depending on the input this gets converted...

struct table inside struct - ASP.NET - allegro webAPI


c#,asp.net,asp.net-web-api,struct
I stopped in one point. I'm writing a small ASP.NET application with WebAPI from polish site allegro.pl (it's similiar to ebay.com) This API have a method which returns me some data: (...) 3. searchArray | SearchResponseType[] Struct table, where are the information about offers that matches the question (...) Inside...

Creating a list of items with different tags + filter


javascript,html,list,filter
I have prepared an example what I would like to produce: link. I have already looked for something and I have found the way to create a filter but just for one value... In my case I need more values all together combined. So that if I wanted a flat...

Can't access any of Linq methods


linq,asp.net-web-api
I'm writing a simple ApiController for getting product stocks, but I'm having a strange issue. I get the data from a method that returns a System.Linq.IQueryable (In a library), but I can't apply any of the Linq methods, like Count or ToList(). The import directive is present and doesn't report...

How to specify callback function when filtering array with object elements in php?


php,arrays,filter
I have an array whose items are of a certain object type, let it be my_object. The class defining the my_objects has a function that I want to use to filter the array. How can I specify that function when calling array_filter? class my_class{ private $exclude; public filter_function(){ return !$this->exclude;...

Web Api and where should I contorol Request Header data


asp.net-web-api,asp.net-web-api2
In Asp.net Web Api, I want to control, request "access token" key is (which is in request header) valid or not. But I cound't decide where should I implement this kind of control. ActionFilter or controller constructor etc. etc.

Null parameter on web api post method


c#,asp.net,asp.net-web-api
I have a very simple web api controller: public class CarrinhoController : ApiController { [HttpPost] public string Adiciona([FromBody] string conteudo) { return "<status>sucesso</status"; } } Now I'm running the server and trying to test this method via curl like this: curl --data "teste" http://localhost:52603/api/carrinho The request is arriving in my...

How can I filter instances of a model in django, with a queryset value of filter field?


python,django,filter
I am creating an application in django, and I have the next question: I want to filet objects of modelA, by the field att1, and I have a queryset of values of the field att1. I mean, my models are: class modelA(models.Model): att1 = models.ForeignKey(modelB) ... class modelB(models.Model): ... I...

How to subset by distinct rows in a data frame or matrix?


r,matrix,filter,data.frame,subset
Suppose I had the following matrix: matrix(c(1,1,2,1,2,3,2,1,3,2,2,1),ncol=3) Result: [,1] [,2] [,3] [1,] 1 2 3 [2,] 1 3 2 [3,] 2 2 2 [4,] 1 1 1 How can I filter/subset this matrix by whether or not each row has duplicate values? For example, in this case, I would only...

Web api with mvc 6 get element based on string


c#,asp.net-mvc,asp.net-web-api,asp.net-5,asp.net-mvc-6
I am creating a web api using mvc 6. now i am trying to get a element from my db. the key in this table is a string (email adress). i do not have acces to this database so i cant change the key of this table. Now when creating...

Losing HttpContext with async await in ASP.NET Identity GetRolesAsync


c#,asp.net-web-api,async-await,asp.net-identity
This is more of an async/await question than ASP.NET Identity. I am using Asp.Net Identity, and have a custom UserStore, with a customized GetRolesAsync method. The UserManager is called from a WebApi controller. public class MyWebApiController { private MyUserManager manager = new MyUserManager(new MyUserStore()); [HttpGet] public async Task<bool> MyWebApiMethod(int x)...

.NET web API calls are getting intercepted by angular js UI Router, returning HTML instead of calling API


javascript,angularjs,asp.net-web-api
I have an angularjs app, that sits on top of an MVC5 app and an WEB API backend. I am using UI Router for the Angular js routing and for now, have removed ALL $urlRouterProvider.when and $urlRouterProvider.otherwise calls, but still when I try to do a $http:get... it is returning...

Filter array by common object property in Angular.js?


javascript,arrays,json,angularjs,filter
I've been struggling with this over a few hours. The situation is, I have an app, that receives data about people in this JSON format: "people": [ { "name": "Ivan", "city": "Moscow", "country": "Russia" }, { "name": "John", "city": "Seattle", "country": "United States" }, { "name": "Michael", "city": "Seattle", "country":...