我正在尝试使用asp.net将数据发布到javarest服务。当我尝试调用服务时,我得到错误
未能加载资源:服务器的响应状态为400(错误请求)。
请指导我,我在谷歌上搜索了一下,但没有找到解决方案。我通过添加下面提到的代码,使我的服务能够在cors域中工作
服务器内应用
@RequestMapping(value = "/create", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody Status addEmployee(@RequestBody Employee employee, HttpServletRequest request, HttpServletResponse response) {
try {
response.addHeader("Access-Control-Allow-Origin","*");
dataServices.addEntity(employee);
return new Status(1, "Employee added Successfully !");
} catch (Exception e) {
// e.printStackTrace();
return new Status(0, e.toString());
}
}
在asp.net应用程序中
$.ajax({
crossDomain: true,
type: 'POST',
url: "http://localhost:9091/employeeservice/employee/create",
data: JSON.stringify({
"id": 10,
"first_name": "narayan",
"last_name": "bhat",
"email": "farah@gmail.com",
"phone": "4545454545"
}),
error: OnErrorCall,
success: OnSuccessCall,
dataType: "json",
contentType: "application/json"
});
function OnSuccessCall(response) {
alert(response.d);
}
function OnErrorCall(response) {
alert(response.status + " " + response.statusText);
}
请指导我,我是asp.net的新手。
我建议你至少尝试RestSharp发布&从Rest API获取响应。如果要使用Rest API代码-后,此方法非常有用。
几天前,我尝试过用您的方式呼叫Rest Services,但从服务器收到了400错误。在那之后,我尝试了RestSharp,它对我有效。
您可以提出请求&使用RestSharp:获得如下响应
var restClient = new RestClient("https://www.example.com");
var request = new RestRequest(Method.POST);
request.Resource = "{version}/adduser";
request.AddParameter("version", "v1", ParameterType.UrlSegment);
request.AddParameter("email", "abc@example.com");
request.AddParameter("password", "abc123");
var response = restClient.Execute(request);
lblMessage.Text = response.Content;