Asp.net Web Api query string parameter with dash

百般思念 提交于 2020-01-22 14:52:08

问题


I have an Web.Api search method which receives the following parameter:

[DataContract(Namespace = "", Name = "search")]
public class SearchParameters
{
    [DataMember(Name = "property-name")]
    public string PropertyName { get; set; }
}

In the Controller, i have this action:

[HttpGet]
public void Search([FromUri]SearchParameters request)
{
    var parameters = 1;
}

I am trying to create a friendly name for PropertyName property (property-name), but the model binder doesn't recognizes the parameter:

/api/changeLog/search?propertyName=asd  // Works

/api/changeLog/search?property-name=asd // Doesn't work

Is dash a reserved query string character? or i am using it wrong?


回答1:


Indeed, it is reserved as defined in http://tools.ietf.org/html/rfc3986 (the standard page for RFC 3986, which defines Uniform Resource Identifiers, otherwise known as URI's).

EDIT I was too quick -- I misread a '=' for a '-' in the list of reserved characters. It seems that the dash is indeed listed with the unreserved characters. It makes no sense to me but that is just my opinion... This RFC being the official standard, you would expect servers to respect the format -- and possibly IIS does, but probably .NET doesn't (see below). End of Edit

Generally query strings follow the format ITEM '&' ITEM... where you can define ITEM as VARIABLE '=' VALUE.

But just like in programming languages, VARIABLE cannot contain any characters that make it hard to parse the name or to map it to a variable. So characters such as '*' and '-' cannot be used in variable names.

EDIT In the case of .NET, I would expect that this is because .NET attempts to map a query string parameter name to a method parameter name. But then they should allow the use of a dash in the [DataMember] attribute. As this is not the case, I assume they did not consult the RFC when they were building this functionality... Would anyone care to elaborate? End of edit

Other sources for the same information:

  • http://en.wikipedia.org/wiki/URI_scheme
  • http://en.wikipedia.org/wiki/Uniform_resource_identifier
  • http://www.rfc-editor.org/rfc/rfc3986.txt


来源:https://stackoverflow.com/questions/22145543/asp-net-web-api-query-string-parameter-with-dash

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!