简体   繁体   中英

asp.net core 3 webapi : Route or Bind parameters (query or posted) with hyphens in their name

I hoped that an Action signature like

[HttpPost]
public string Post(string thirdPartySpecifiedParameter)

would automagically bind a hyphenated query parameter

controller?third-party-specified-parameter=value

or a JSON posted value

{ "third-party-specified-parameter":"value" }

and assign it to thirdPartySpecifiedParameter but it doesn't. The routing docs deal with the example of mapping hyphens in Urls paths, but not with binding parameter & field names which are invalid for C#.

What's the simplest way to bind the incoming hyphenated name to the matching C# parameter?

First off, the problem is about Binding not Routing, and the simplest available solution is using a BindingAttribute provide by.Net. The limitation -- not a new one -- is that you need a different BindingAttribute for Query parameters vs Json Body vs Form post.

[HttpPost]
public string Post(
    [FromBody]PostModel model,
    [FromQuery(Name="kebab-case-query-param")]string kebabCaseQueryParam)

The [FromQuery(Name="...")] deals with query string parameters

For Json posts, you must use the [FromBody] attribute in the method signature, and define a model, and put an Attribute on the property to bind. Newtonsoft.Json or new-in-core-3 System.Text.Json use slightly different Attribute names:

public class PostModel
{
    //This one if you are using Newtonsoft.Json
    [JsonProperty(PropertyName = "kebab-case-json-field")]

    //This one of you are using the new System.Text.Json.Serialization
    [JsonPropertyName("kebab-case-json-field")]

    public string kebabCaseProperty { get; set; }
}

Back in your Startup.cs , to use Newtonsoft, you also need AddMvc() , whereas for new System.Text.Json , you don't. Something like this:

    public void ConfigureServices(IServiceCollection services)
    {
        //if using NewtonSoft
        services.AddMvc().AddNewtonsoftJson();
    
        //if using System.Text.Json
        //dotnet new webapi for netcore3 generates this code:
        services.AddControllers();
        
    }

To use Newtonsoft Json this way under NetCore3, you depend on nuget package Microsoft.AspNetCore.Mvc.NewtonsoftJson

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM