question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Overriding the controller methods

See original GitHub issue

Description

Hello, i’ve a question (and i think there is a problem in here) I’ve a controller named GamesController, and i want to override the patch method to change some properties on the fly. So i’ve change the controllers content similar to this.

Controller

    [Authorize]
    [Route("jsonapi/[controller]")]
    public class GamesController : JsonApiController<Game>
    {
        public GamesController(
            IJsonApiContext jsonApiContext,
            IResourceService<Game> resourceService,
            ILoggerFactory loggerFactory)
            : base(jsonApiContext, resourceService, loggerFactory)
        {
        }
 
        [HttpPatch("{id}")]
        public override Task<IActionResult> PatchAsync(int id, [FromBody] Game entity)
        {
            //Force to change some property of entity <------ question is here
            entity.Title = $"{entity.Title} {DateTime.Today.ToShortDateString()}";
            return base.PatchAsync(id, entity);
        }
    }

Sample request body

{
 "data": {
  "type": "games",
  "attributes": {
       "title": "My game"
     }
   }
}

Actually it’s working without giving an error, but not accepting the value change.

Summary

  • Current title at the Db: “Old game”
  • Sent title: “My game”
  • Changed title via controller: “My game 03.03.2019” (i can see this value in the quickwatch)
  • Database record after the patch operation: “My game” (this is the problem) Expected database record after the patch operation: “My game 03.03.2019”

Environment

  • JsonApiDotNetCore Version: 3.1.0
  • Other Relevant Package Versions:
    • Net Core: 2.2.0

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:9 (6 by maintainers)

github_iconTop GitHub Comments

2reactions
milosloubcommented, Mar 4, 2019

Sorry for previous post, there was mistake. For updating values there is JsonApiContext (IIJsonApiContext param of your Controller), which is holder of changed attributes from PATCH request.

You should store jsonApiContext to private variable and do this

        [HttpPatch("{id}")]
        public override Task<IActionResult> PatchAsync(int id, [FromBody] Game entity)
        {
            //Force to change some property of entity <------ question is here
            var titleAttr = _jsonApiContext.AttributesToUpdate.FirstOrDefault(i => i.Key.InternalAttributeName == nameof(Game.Title));
            if (titleAttr.Key != null)
                _jsonApiContext.AttributesToUpdate[titleAttr.Key] = $"{entity.Title} {DateTime.Today.ToShortDateString()}";
            
            return base.PatchAsync(id, entity);
        }
1reaction
milosloubcommented, Mar 4, 2019

There is the limitation comming from HttpPatch itself. HttpPatch reflects only truly changed attributes. For example, you have Game entity, you send PATCH on your title attribute, then you face several problems:

  1. input Game model holds only Title property filled and all the others are null (or default values). If you send this to DB via context.SaveChanges(), you will reset all the other properties.
  2. you can send NULL to your title property and then you are not able to distinguish if it’s comming from PATCH or if it’s default value when Game instance is created.
  3. you will face the same problem in case of navigation properties (relationships) -> you are not able to distinguish wheter you want to unset relationship or if it is just default value comming from new instance.

That’s the reasons why AttributesToUpdate and RelationshipsToUpdate exists. .NET Core itself uses JsonPatchDocument https://dotnetcoretutorials.com/2017/11/29/json-patch-asp-net-core/ but it’s coupled with application/json-patch+json standard and it’s quite overkill when api needs only application/vnd.api+json

Read more comments on GitHub >

github_iconTop Results From Across the Web

Overriding MVC Controller When Controller In a Separate ...
However, I want to override certain Controller functions based on which project (a.k.a. "site") is calling the function.
Read more >
Why and how to override Laravel's built-in auth controller ...
We can replace (or overwrite) them by creating the same method name in our class, but then we can't use parent::getLogin() to call...
Read more >
Overriding the index method on a controller · Issue #320
I'm trying to display all the users that aren't administrators in my users dashboard. def index super @resources = User.where(admin: ...
Read more >
Can I override controller method (not action method) in plugin
So want to override below method (not action method) in Nop plugin. i.e. where ever this method is called in Nop core code,...
Read more >
How to Override an Existing Controller in Odoo 14
To override a controller, you have to create a subclass to define existing functions. Now select a function from the controller for ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found