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
No comments:
Post a Comment