Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ApiController returns 404 when ID contains period

I have an ApiController and I want to use email addresses as the ID parameter for requests:

// GET api/employees/[email protected] public CompactEmployee Get(string id) {    var email = id;    return GetEmployeeByEmail(email); } 

However, I cannot get this to work (returns 404):

http://localhost:1080/api/employees/[email protected]

The following all work:

  • http://localhost:1080/api/employees/employee@company
  • http://localhost:1080/api/employees/employee@company.
  • http://localhost:1080/api/[email protected]

I have set relaxedUrlToFileSystemMapping="true" in my web.config as detailed by Phil Haack.

I would very much love the full email address to work, but any time the period is followed by any other character, the request returns a 404. Any help would be greatly appreciated!

Solution

Due to a lack of other options, I've headed in the direction Maggie suggested and used the answer from this question to create a rewrite rule to automatically append a trailing slash when I need an email in the URL.

<system.webServer>   ....      <rewrite>     <rules>       <rule name="Add trailing slash" stopProcessing="true">         <match url="^(api/employees/.*\.[a-z]{2,4})$" />         <action type="Rewrite" url="{R:1}/" />       </rule>     </rules>   </rewrite> </system.webServer> 
like image 703
Jonathan Freeland Avatar asked Nov 08 '12 21:11

Jonathan Freeland


People also ask

How does Web API handle 404 error?

A simple solution is to check for the HTTP status code 404 in the response. If found, you can redirect the control to a page that exists. The following code snippet illustrates how you can write the necessary code in the Configure method of the Startup class to redirect to the home page if a 404 error has occurred.

Can Apicontroller return view?

You can return one or the other, not both. Frankly, a WebAPI controller returns nothing but data, never a view page. A MVC controller returns view pages.

What is Apicontroller C#?

Web API Controller is similar to ASP.NET MVC controller. It handles incoming HTTP requests and send response back to the caller. Web API controller is a class which can be created under the Controllers folder or any other folder under your project's root folder.

What is IHttpActionResult in Web API c#?

The IHttpActionResult interface was introduced in Web API 2. Essentially, it defines an HttpResponseMessage factory. Here are some advantages of using the IHttpActionResult interface: Simplifies unit testing your controllers. Moves common logic for creating HTTP responses into separate classes.


1 Answers

Would adding a trailing slash work for your scenario?

http://localhost:33021/api/employees/[email protected]/ 
like image 185
Maggie Ying Avatar answered Oct 04 '22 18:10

Maggie Ying