Home > Backend Development > C++ > How to Handle URLs with Special Characters in ASP.NET Web API 2 Routing?

How to Handle URLs with Special Characters in ASP.NET Web API 2 Routing?

Barbara Streisand
Release: 2025-01-05 03:19:42
Original
822 people have browsed it

How to Handle URLs with Special Characters in ASP.NET Web API 2 Routing?

Routing with Special Characters in MVC Web API 2

Problem:
Attempting to access resources using URLs containing special characters, such as dots (`.') in the path segment, results in a "HTTP Error 404.0 - Not Found" error.

Configuration:
The sample controller and WebApiConfig provided in the question:

// PeopleController.cs
public class PeopleController : ApiController
{
    // ...
}

// WebApiConfig.cs
public static void Register(HttpConfiguration config)
{
    // ...

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

Solution:
To allow special characters in the path segment, such as dots, modify the WebApiConfig route as follows:

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

This route template adds a catch-all route parameter named {*path} that captures any remaining path segments, including special characters like dots.

Example:

http://somedomain.com/api/people/staff.33311/
Copy after login

By appending a slash (/) to the end of the URL, the request can be routed to the controller action that handles the path segment, in this case staff.33311.

The above is the detailed content of How to Handle URLs with Special Characters in ASP.NET Web API 2 Routing?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template