Hasan009 Hasan009 - 4 months ago 53
C# Question

How to Post a Custom Named Method in Web Api ?

I am new in Web Api. I am Create a web Api Controller with custom named actions. I am calling this from a WPF client using HttpClient. But I get an error
response status code does not indicate success 404 (Not Found)

Here Is My Web Api Controller :

public class ActivationController : ApiController
{
private readonly IActivationUnit _activationUnit;

public ActivationController()
{
_activationUnit = new ActivationUnit();
}

// api/activation/GetAllActivisionInformations
public HttpResponseMessage GetAllActivationInformations(string username)
{
return Request.CreateResponse(HttpStatusCode.OK, _activationUnit.ActivationRepository.GetActivationInformations(username));
}

// api/activation/NewLicense
[HttpPost]
public HttpResponseMessage PostNewLicense(LicenseMetadata licenseMetadata)
{
bool isSuccess = _activationUnit.ActivationRepository.NewLicense(licenseMetadata.Username, licenseMetadata.ActivisionInformation);
if (isSuccess)
{
try
{
_activationUnit.Save();
}
catch (Exception)
{
isSuccess = false;
}
}
return Request.CreateResponse(isSuccess ? HttpStatusCode.OK : HttpStatusCode.BadRequest, isSuccess);
}
}


My Routing is:

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

// Route GET method

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


My Client Code is :

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:42471");
client.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));

var licenseMetadata = new LicenseMetadata
{
ActivisionInformation = new ActivisionInformation(),
Username = "UserName"
};

var response = await client.PostAsJsonAsync("api/activation/NewLicense", licenseMetadata);
try
{
response.EnsureSuccessStatusCode();
MessageBox.Show("Success");

}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}



When I send Request to server using HttpClient then i get response status code does
not indicate success 404 (Not Found)



I was try to change url "api/activation/newlicense" to "api/activation/PostNewLicense" but in this case I get


response status code does not indicate success 500 (Internal Server Error) form HttpClient


Where I am doing wrong. I am already spend two days for it.

I am using :
Visual Studio 2012, .NET 4, MVC 4, Windows 8, IIS 8

Answer

If you don't want to use the default implementation of having a Get/Post in your action names, and instead want to call methods, adjust your routes as you have (just the first one, don't have a 2nd one for get), and stop using the Get and Post prefixes.

Route config:

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

In your Controller:

public class ActivationController : ApiController
{
    // .. other code ..

    // api/Activation/NewLicense
    [HttpPost]
    public HttpResponseMessage NewLicense(LicenseMetadata licenseMetadata)
    {
        // .. rest of your code ..
    }
}

Personally I don't like the default implementation, unless you are trying to create a REST API. The way it works is that you can have GetFooBar and PostBarBaz, it doesn't matter what you have after Get and Post. For my purposes I always override the route as above.