我有一个API,并且在WindowsForm中调用它时出现“请求不能为空”错误。 我怎么称呼Windows Form
[HttpGet]
[Route("")]
public HttpResponseMessage GetNearBeacons()
{
try
{
return Request.CreateResponse(HttpStatusCode.OK, repoNear.List());
}
catch (Exception exp)
{
return Request.CreateErrorResponse(HttpStatusCode.ExpectationFailed, exp);
}
}
通话代码
public void Test(){
BeaconController beaconController = new BeaconController();
beaconController.GetNearBeacons();
}
答案 0 :(得分:0)
您可以从Jquery Ajax调用api。像这样的东西:
$.ajax({
url: '../api/ControllerName/GetNearBeacons',
type: 'GET',
success: function (response) {
},
error: function (response) {
}
});
答案 1 :(得分:0)
我想您正在使用Web API,您在做什么是错误调用API的方式。
Web API是可以通过 HTTP 协议访问的Web API,可以从其他应用程序访问。
您会在下面找到使用邮递员调用Web API的示例,或者您可以使用浏览器将它作为 get 动词就足够了(对于启动Web api时的主机名,它显示在您的浏览器localhost:端口号)
答案 2 :(得分:0)
private void TestApi()
{
try
{
using (var httpClient = new HttpClient())
{
string URI = string.Empty;
string progressAPI = "api/GetNearBeacons";
var baseUrl = @"http://localhost/sample";
var uriBuilder = new UriBuilder(baseUrl)
{
Scheme = Uri.UriSchemeHttp
};
httpClient.BaseAddress = uriBuilder.Uri;
httpClient.DefaultRequestHeaders.Accept.Clear();
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
HttpResponseMessage response = httpClient.GetAsync(progressAPI).Result;
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
WriteErrorLog("Api called successfully StatusCode :" + response.StatusCode + Environment.NewLine);
}
else
{
WriteErrorLog("Api Calling Failed StatusCode :" + response.StatusCode + Environment.NewLine);
}
}
}
catch (WebException ex)
{
WriteErrorLog(ex.GetBaseException().ToString());
}
catch (Exception ex)
{
WriteErrorLog(ex.GetBaseException().ToString());
}
}