User Authorized Attribute

I have a child class AuthorizeAttribute named CheckArticleExistence.

I would like to set the attribute using the parameter that I get in the action. Like this:

[CheckArticleExistence(Id=articleId)]
public ActionResult Tags(int articleId)
{
...
}

I want to use articleId to check if this article exists in the database, and if it is not, I can run something else using the OnAuthorization method.

Is there any way? Thanks.

+3
source share
3 answers

I think you can get articleId from AuthorizationContext, so you do not need to pass it as an attribute property.

You can simply do:

[CheckArticleExistence]
public ActionResult Tags(int articleId)
{
...
}
+3
source

This worked (thanks!):

[CheckArticleExistence]
public ActionResult Tags(int articleId)
{
    ...
}

...

public class CheckArticleExistenceAttribute : AuthorizeAttribute
{
    private int articleId;

    public override void OnAuthorization(AuthorizationContext filterContext)
    {

        this.articleId = int.Parse(filterContext.RouteData.Values["id"].ToString());

        if (!Article.Exists(articleId))
        {
            ...
        }
    }
}
+4
source

You can put the method in your repository to check for an article.

public ActionResult Tags(int articleId)
{
    if (repository.ArticleExists(articleID))
    {
        // Do your thing
    }
    else
    {
        return view("NotFound"); // or do something else
    }
}

Or you can just try to get the article and check the null object.

public ActionResult Tags(int articleId)
{
    var article = repository.GetArticle();
    if (article !=null)
    {
        // Do your thing
    }
    else
    {
        return view("NotFound"); // or do something else
    }
}
+3
source

Source: https://habr.com/ru/post/1718612/


All Articles