Asp.net Web API Routing by action name fix

241 views Asked by At

I found this article at asp.net Learn website. I use this article to help me to create an API method to search in the database by email and not id.

However, if you take a look at the article, you will be able to help me fix my problem as follows:

my controller:

[HttpGet]
public string Details(string email);

[HttpGet]
[ActionName("Email")]
public HttpResponseMessage GetEmail(string email);

My WebApiConfig class

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

First, The error I get for the Details method as follows:

(Error 1 'MyApp.Controllers.UsersController.Details(string)' must declare a body because it is not marked abstract, extern, or partial D:\Abdulrhman A A\MyApp\Asp.net Web API\Controllers\UsersController.cs 40 27 MyAppApplication)

Second, the error I get for the GetEmail method as follows:

(Error 2 'MyApp.Controllers.UsersController.GetEmail(string)' must declare a body because it is not marked abstract, extern, or partial D:\Abdulrhman A A\MyApp\Asp.net Web API\Controllers\UsersController.cs 44 43 MyAppApplication)

1

There are 1 answers

3
dotnetom On BEST ANSWER

The article provides a sample on how to configure routing. These last two samples are just for illustrative purposes, it is more like pseudo-code, not a working code. If you are just starting with C# these last code samples are confusing.

The errors that you are getting clearly describe what is going on - you need a method body. To fix it, instead of adding ; at the end add {} and actually implement the method:

[HttpGet]
public string Details(string email)
{
    // Implement your method, so it returns string
}

[HttpGet]
[ActionName("Email")]
public HttpResponseMessage GetEmail(string email)
{
    // Implement your method so it returns HttpResponseMessage 
}