我是 Web Api 的新手。我正在使用自定义命名操作创建一个 Web Api 控制器。我使用 HttpClient 从 WPF 客户端调用它。但是我得到一个错误 响应状态码不表示成功 404 (Not Found)
这是我的 Web Api 控制器:
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);
}
}
我的路由是:
// 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 }
);
我的客户代码是:
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);
}
当我使用 HttpClient 向服务器发送请求时,我得到响应状态代码不指示成功 404(未找到)
我试图将 url "api/activation/newlicense" 更改为 "api/activation/PostNewLicense" 但在这种情况下我得到
响应状态码不表示成功 500 (Internal Server Error) form HttpClient
我在哪里做错了。我已经花了两天时间。
我正在使用:Visual Studio 2012、.NET 4、MVC 4、Windows 8、IIS 8