将属性添加到继承的函数c#

时间:2018-01-11 00:12:12

标签: c# inheritance asp.net-web-api asp.net-core attributes

我正在使用.net Core上的webapi应用程序,我有一个基本控制器,所有其他控制器都来自该控制器。

这是班级:

#include <tuple>
#include <iostream>
#include <type_traits>

int func(int a)
 { return a+1; }

template <typename T, std::size_t>
using typer = T;

template <typename>
struct bar;

template <>
struct bar<std::index_sequence<>>
 { 
   static void f () {}
 };

template <std::size_t ... Is>
struct bar<std::index_sequence<Is...>>
   : public bar<std::make_index_sequence<sizeof...(Is)-1U>>
 {
   using bar<std::make_index_sequence<sizeof...(Is)-1U>>::f;

   static auto f (typer<int, Is>... as)
    { return std::make_tuple(func(as)...); }
 };

template <std::size_t N = 64U>
struct foo : public bar<std::make_index_sequence<N>>
 { };

int main ()
 {    
   auto [v1, v2, v3] = foo<>::f(1, 2, 3);

   std::cout << v1 << ", " << v2 << ", " << v3 << std::endl;
 }

但是,我的某些API端点不需要Authorize属性。所以我创建了另一个基本控制器:

Dim strPrompt As String, strname As String
Dim sreplace As String, mychar As Variant, strdate As String
Dim M As String            ' variable used to store userform info
M = Me.EvalID_T1.Text     ' userform info
    For Each mychar In Array("/", "\", ":", "?", Chr(34), "<", ">", "¦")
       strname = Replace(strname, mychar, sreplace)
       strdate = Replace(strdate, mychar, sreplace)
   Next mychar
    myPath = "C:\Users\cam\Desktop\Test\ & " - path to save file
    If myPath = False Then
        MsgBox "No directory chosen !", vbExclamation
    Else
    On Error Resume Next
        olmail.SaveAs myPath & M & ".msg", olMsg   ' unknown how to modify

您可能已经注意到,除了[Authorize]属性之外,控制器是相同的。有没有办法在不需要创建新控制器的情况下完成这项工作?

干杯!

1 个答案:

答案 0 :(得分:1)

创建没有授权属性的基本控制器。

public class ReadOnlyBaseController<TEntity, TEntityResource> : Controller {
    protected readonly IMapper mapper;
    protected readonly IBaseUnitOfWork unitOfWork;
    protected readonly IBaseRepository<TEntity> repository;

    public ReadOnlyBaseController(
        IBaseRepository<TEntity> repository, IBaseUnitOfWork unitOfWork, IMapper mapper) {
        //...
    }

    [HttpGet]
    public virtual async Task<IActionResult> Get() {
        //..
    }

    [HttpGet("Id")]
    public virtual IActionResult GeSingle(int Id) { 
        //...
    }
}

然后在需要auth的派生控制器中,您可以将其添加到控制器本身

[Authorize]
public class ReadOnlyOAuthController<TEntity, TEntityResource> : ReadOnlyBaseController<TEntity, TEntityResource> {

    public ReadOnlyOAuthController(
        IBaseRepository<TEntity> repository, IBaseUnitOfWork unitOfWork, IMapper mapper) 
            : base(repository, unitOfWork, mapper) {
    }

    [AllowAnonymous]
    [HttpGet("someaction")]
    public IAction SomeOtherAction() {
        //...
    }
}

[Authorize]属性将应用于派生控制器上的所有操作,如果您想允许操作,则可以使用[AllowAnonymous]属性。