Fil*_*lah 7 c# json asp.net-web-api angularjs asp.net-core
在前端我使用Angular从表单收集som数据并将其发送到我的服务器端控制器.如下图所示,我在我的控制器和服务上获取数据($ scope.newData),但当它到达服务器时,我收到以下错误:"不支持的媒体类型",我的newData为空.
我的控制器:
// Create new salesman
$scope.addSalesman = function (newData) {
console.log("Controller");
console.log($scope.newData);
myService.addNewSalesman($scope.newData).then(function (data) {
console.log(data);
}, function (err) {
console.log(err);
});
};
Run Code Online (Sandbox Code Playgroud)
我的服务:
addNewSalesman: function (newData) {
console.log("service");
console.log(newData)
var deferred = $q.defer();
$http({
method: 'POST',
url: '/api/Salesman',
headers: { 'Content-type': 'application/json' }
}, newData).then(function (res) {
deferred.resolve(res.data);
}, function (res) {
deferred.reject(res);
});
return deferred.promise;
}
Run Code Online (Sandbox Code Playgroud)
我的推销员型号:
public class Salesman
{
public int SalesmanID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Gender { get; set; }
public string BirthDate { get; set; }
public int Phone { get; set; }
public string Adress { get; set; }
public string City { get; set; }
public int Postal { get; set; }
public string Role { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我的服务器端控制器:
[Route("api/[controller]")]
public class SalesmanController : Controller
{
private readonly DataAccess _DataAccess;
public SalesmanController()
{
_DataAccess = new DataAccess();
}
[HttpPost]
public IActionResult PostSalesman([FromBody] Salesman newData)
{
return Ok(newData);
}
Run Code Online (Sandbox Code Playgroud)
您发送的标题错误。您正在发送Content-Type: application/json,但是您必须发送Accept: application/json。
Content-Type: application/json是服务器必须发送给客户端的内容,客户端必须发送此消息Accept以告知服务器它接受哪种响应。
addNewSalesman: function (newData) {
console.log("service");
console.log(newData)
var deferred = $q.defer();
$http({
method: 'POST',
url: '/api/Salesman',
headers: { 'Accept': 'application/json' }
}, newData).then(function (res) {
deferred.resolve(res.data);
}, function (res) {
deferred.reject(res);
});
return deferred.promise;
}
Run Code Online (Sandbox Code Playgroud)
应该做。另请参阅MDN上的“ 内容协商 ”。
这是一个CORS问题.
在开发过程中,可以安全地接受来自所有来源的所有http请求方法.将以下内容添加到startup.cs:
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
loggerFactory.AddConsole(Configuration.GetSection("Logging"));
loggerFactory.AddDebug();
//Accept All HTTP Request Methods from all origins
app.UseCors(builder =>
builder.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod());
app.UseMvc();
}
Run Code Online (Sandbox Code Playgroud)
有关CORS的更多详细信息,请参见此处.
| 归档时间: |
|
| 查看次数: |
23752 次 |
| 最近记录: |