5

Hi im tyring to exlude one property from my model when it reaches my action in the controller (Web API),

i tried [Bind(Exclude ="something")] but it seems that its not apart of .net core api

2
  • stackoverflow.com/q/55665609/2410655 Commented Sep 27, 2019 at 21:19
  • iirc [Bind] only works for multipart/form (MVC actions), not WebAPi which uses json/xml payloads. But if you use proper ViewModel classes (they should only contain values required for a specific action), excluding isn't necessary at all Commented Sep 27, 2019 at 21:31

3 Answers 3

8

If you are on ASP.NET Core, Use the Microsoft.AspNetCore.Mvc.ModelBinding.BindNeverAttribute attribute ([BindNever]).

public class ExampleViewModel
{
    // ResponseMessage will not participate in model binding.

    [BindNever]
    public string ResponseMessage { get; set; }
}

https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.modelbinding.bindneverattribute?view=aspnetcore-5.0

"Indicates that a property should be excluded from model binding. When applied to a property, the model binding system excludes that property. When applied to a type, the model binding system excludes all properties that type defines."

Sign up to request clarification or add additional context in comments.

1 Comment

You may also need [ValidateNever] - (look at the stacktrace for any validation related stack frames). But if you're trying to block based upon that, consider renaming the property to a method GetResponseMessage().
5

[Bind] attribute does not work for the web api if you receive the model as json, try to use [JsonIgnore] on the model properties which need to be excluded:

public class MyModel
{
    [JsonIgnore]
    public string Name { get; set; }
    //...
}

Action:

[HttpPost]
public IActionResult Student([FromBody]MyModel model)

Comments

0

You can use ViewModel and bind your view with model binder although if your field which you want to exclude if not null then your model state validation couldn't fail

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.