user2445773
user2445773

Reputation: 31

Unable to make Type.GetType(string TypeName) method and MemberInfo.CustomAttributes property available in DNX Core 5.0

I am trying to get the attributes on the controller and methods of the controller, but I can not seem to make the necessary methods and properties available in DNX Core 5.0. I want to get what roles the user needs to access a given method. For example, if I have this

 [Authorize(Roles = "Admin")]
 public class UserController : Controller
 {
    public IActionResult Index()
    {
        return View();
    }
}

I want to be able to get that the user needs the Admin role to be able to access this controller. My project.json file for dnxcore50 looks like this:

"dnxcore50": {
  "dependencies": {
    "System.Collections": "4.0.10-beta-*",
    "System.Collections.Concurrent": "4.0.10-beta-*",
    "System.IO": "4.0.10-beta-*",
    "System.Linq": "4.0.0-beta-*",
    "System.Linq.Expressions": "4.0.10-beta-*",
    "System.Reflection": "4.0.10-beta-*",
    "System.Reflection.Emit": "4.0.0-beta-*",
    "System.Reflection.Emit.Lightweight": "4.0.0-beta-*",
    "System.Reflection.Extensions": "4.0.0-beta-*",
    "System.Reflection.TypeExtensions": "4.0.0-beta-*",
    "System.Reflection.Primitives": "4.0.0-beta-*",
    "System.Runtime": "4.0.20-*",
    "System.Runtime.Extensions": "4.0.10-beta-*",
    "System.Runtime.CompilerServices.VisualC": "4.0.0-beta-*",
    "System.Runtime.InteropServices": "4.0.20-beta-*",
    "System.Text.Encoding": "4.0.10-beta-*",
    "System.Text.RegularExpressions": "4.0.10-beta-*",
    "System.Threading": "4.0.10-beta-*"
  }
}    

Any ideas on how I would get the necessary methods/properties to become available in DNX Core 5.0 or have any other suggestions on how to approach this problem?

Upvotes: 3

Views: 700

Answers (1)

Adrien Constant
Adrien Constant

Reputation: 576

If you look at the source code on github, you can see how it is handled (line 94) :

https://github.com/aspnet/Mvc/blob/eef6c3883a7e27b8387b0925f0b6a88df0a484c5/src/Microsoft.AspNet.Mvc.Core/ModelBinding/Metadata/ModelAttributes.cs

As you can see, you have to use GetTypeInfo() to use the GetCustomAttributes() method. In your code, you can do :

using System.Reflection;
...
obj.GetType().GetTypeInfo().GetCustomAttributes();

Upvotes: 3

Related Questions