Home >Backend Development >C++ >How to Handle Dot Characters in MVC Web API 2 URL Parameters?

How to Handle Dot Characters in MVC Web API 2 URL Parameters?

Patricia Arquette
Patricia ArquetteOriginal
2025-01-05 08:11:44239browse

How to Handle Dot Characters in MVC Web API 2 URL Parameters?

How to Accommodate Dot Characters in MVC Web API 2 URL Parameters

In MVC Web API 2 applications, it can be desirable to allow URL parameters to contain dot characters (".") for compatibility with certain URL formats. However, by default, the framework considers dots as route separators and generates HTTP 404 errors when these characters are present.

Problem:

The following URL, which attempts to retrieve a person with ID "staff.33311," throws a 404 error:

http://somedomain.com/api/people/staff.33311

Default Route Configuration:

config.Routes.MapHttpRoute(
    name: "DefaultApi",
    routeTemplate: "api/{controller}/{id}",
    defaults: new { id = RouteParameter.Optional }
);

This route configuration assumes that "id" is a single segment, and dots are not allowed within it.

Solution:

To allow dots in URL parameters, you can append a trailing slash to the URL. This signals to ASP.NET MVC that the parameter continues beyond the first segment.

http://somedomain.com/api/people/staff.33311/

By adding the slash, the route becomes:

api/{controller}/{id}/{trailingSegment}

ASP.NET MVC will now interpret "staff.33311" as the value for the "id" parameter.

Example

With the updated route configuration, the following code in the PeopleController will successfully handle the URL with the dot character:

public IHttpActionResult GetPerson(string id)
{
    var person = _people.FirstOrDefault(p => p.Id.ToLower().Equals(id.ToLower()));
    if (person == null)
        return NotFound();

    return Ok(person);
}

The above is the detailed content of How to Handle Dot Characters in MVC Web API 2 URL Parameters?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn