Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

SmartEnum binding to [FromQuery] parameters #410

Open
laska-u opened this issue Jul 25, 2023 · 3 comments
Open

SmartEnum binding to [FromQuery] parameters #410

laska-u opened this issue Jul 25, 2023 · 3 comments

Comments

@laska-u
Copy link

laska-u commented Jul 25, 2023

I have a controller that binds string parameters from GET request into a class object.
I tried to use JsonConverter attributes with SmartEnum name serialization to automatically bind some parameter to a SmartEnum objects but it always NULL. Is there a workaround in this situation?

@ShawInnes
Copy link

Sorry this doesn't directly answer your question, but I've managed to find a workaround by making my [FromQuery] object use a string type... It's not as clean, but it does the job.

on my Controller:

    public async Task<IActionResult> GetPepVariants([FromQuery] GetAdminPepVariantsQuery request) =>

The request type:

public class GetAdminPepVariantsQuery
{
    ...
    public string? PepType { get; set; }
    ...
}

The EF query (or any other use)

query = query.Where(p => p.PepType == PepType.FromName(request.PepType, true));

@miroslavgrozdanovski
Copy link

@laska-u, when the data is not really a JSON coming from a request body, the JsonConverters are not executed. I just encountered the same issue, and there are two options that worked for me:

  1. Use a custom TypeConverter as described in the Microsoft docs. Their example uses a GeoPoint type, but in our example with SmartEnums, you would just convert by calling FromValue(s).
  2. If you are using .NET 7, you can just add a TryParse implementation in your SmartEnum, and the framework will call it. Here is an example of that in the release notes of .NET 7 preview 3.

You can also use a custom model binder, but I didn't try that option as it's not needed.

@ardalis, should any of these options be added into the library? I'm open on contributing if you agree.

@ardalis
Copy link
Owner

ardalis commented Sep 5, 2023

@miroslavgrozdanovski Sure, that would be great. I probably need to improve the docs for SmartEnum some time as well, to cover things like this that aren't necessarily "in the box"...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants