我需要在不使用模型的情况下向/从C#API发送/接收数据。
我出于测试目的,下面的JS:
fetch('/login', {
method: 'post',
body: JSON.stringify({
email: 'hasan@gmail.com', //document.getElementById('email').value
pswd: '1234' //document.getElementById('answer').value
})
})
.then(function(response) {
return response.text();
// return response.json();
}).then(function(text) {
// console.log(text);
});
我需要发送用户名和密码,并需要服务器发回一些确认信息。
C#中使用的控制器是:
[Route("/login")]
public class FetchController
{
[HttpPost]
public async Task Post(String loginParam)
{
if (loginParam != null)
{
Console.WriteLine("Login Data Recieved");
}
else
{
Console.WriteLine("Login Data is NULL");
}
Console.WriteLine(loginParam);
var response = _httpContextAccessor.HttpContext.Response;
response.Headers.Add("Content-Type", "text/event-stream");
response.StatusCode = 200;
await response
.WriteAsync($"user logged in at {DateTime.Now}\r\r");
response.Body.Flush();
}
}
在这里,我一直收到Login data is NULL
,我知道这是因为我没有将登录数据绑定到Model class
,所以如何使用{{1}使上述工作WITHOUT
}}
答案 0 :(得分:1)
请注意,您必须匹配参数名称,并尝试将参数标记为[FromBody],因为webapi将尝试将其作为fromUrl读取。
以下是一份工作样本:
function callFnc() {
var loginParam = JSON.stringify({ email: 'hasan@gmail.com', pswd: '1234' });
$.post("/Fetch/login", { loginParam : loginParam })
.done(function (data) {
alert("Data Loaded: " + data);
});
}
<强> C#强>
[HttpPost]
public ActionResult Login(string loginParam)
{
if (loginParam != null)
{
Console.WriteLine("Login Data Recieved");
}
else
{
Console.WriteLine("Login Data is NULL");
}
Console.WriteLine(loginParam);
return new JsonResult() { Data = "Ok" };
}
ps:样本是mvc而不是webapi,但它们是相似的
注意:你在这里的问题不在c#中,它只是在获取APi中,如果可以的话,摆脱它。
以下是我使用Fetch制作的示例
<强>的Javascript 强>
function useFetch() {
var loginParam = JSON.stringify({ email: 'hasan@gmail.com', pswd: '1234' });
fetch('/Home/login', {
method: 'post',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: loginParam
});
}
<强> C#强>
[HttpPost]
public JsonResult Login([FromBody]object loginParam)
{
if (loginParam != null)
{
Console.WriteLine("Login Data Recieved");
}
else
{
Console.WriteLine("Login Data is NULL");
}
Console.WriteLine(loginParam);
return Json("OK");
}
答案 1 :(得分:0)
虽然我接受了E.B.回答,但我只是想重新编写下面的完整工作代码,因为它可能会对将来的某些人有所帮助:
project.json
:
{
"version": "1.0.0-*",
"buildOptions": {
"debugType": "portable",
"emitEntryPoint": true
},
"dependencies": {
"Microsoft.AspNetCore.Server.Kestrel": "1.0.1",
"Microsoft.AspNetCore.Mvc": "1.0.1",
"Microsoft.AspNetCore.StaticFiles": "1.0.0",
"Microsoft.AspNetCore.Cors":"1.0.0"
},
"frameworks": {
"netcoreapp1.0": {
"dependencies": {
"Microsoft.NETCore.App": {
"type": "platform",
"version": "1.0.1"
}
},
"imports": "dnxcore50"
}
}
}
Program.cs
:
using System.IO; // for Directory
using Microsoft.AspNetCore.Hosting; // for WebHostBuilder()
namespace ApiCall
{
public class Program
{
public static void Main(string[] args)
{
var host = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.UseStartup<Startup>()
.Build();
host.Run();
}
}
}
Startup.cs
:
using Microsoft.AspNetCore.Builder; // for IApplicationBuilder and FileServerOptions
using Microsoft.AspNetCore.Hosting; // for IHostingEnvironment
using Microsoft.Extensions.DependencyInjection; // for IServiceCollection
namespace ApiCall
{
public class Startup
{
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddCors(); // to be accesssed from external sites, i.e. outside the server
// Add framework services.
services.AddMvc(); // to use Controllers
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseFileServer(); // to be accessed from files in the server inside wwwroot folde
app.UseCors(builder => // to be accesssed from external sites, i.e. outside the server
builder.AllowAnyOrigin()
.AllowAnyHeader()
.AllowAnyMethod()
.AllowCredentials()
);
app.UseMvc();
}
}
}
Controllers / FetchController.cs
:
using System; // for Console.WriteLine
using Microsoft.AspNetCore.Mvc; // for Controller, [Route], [HttpPost], [FromBody], JsonResult and Json
namespace ApiCall.Controllers
{
[Route("api/[controller]")]
public class FetchController : Controller
{
// POST api/values
[HttpPost]
public JsonResult Post([FromBody]object loginParam)
{
Console.WriteLine(loginParam);
return Json(loginParam);
}
}
}
wwwroot / index.html
:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
</head>
<body>
<h2>
Test page for using ajax call in webapi core.
</h2>
<button id="btnUseFetch" onclick="useFetch()" class="btn btn-danger">Use Fetch</button>
<script type="text/javascript">
function useFetch() {
var loginParam = JSON.stringify({ email: 'hasan@gmail.com', pswd: '1234' });
fetch('/api/Fetch', { // or 'http://localhost:5000/api/Fetch' in external file
method: 'post',
headers: new Headers({
'Content-Type': 'application/json'
}),
body: loginParam
}).then(function(response) {
return response.json();
}).then(function(returnedValue) {
var asdf = returnedValue;
console.log(asdf);
}).catch(function (err) {
console.log(JSON.stringify(err));
});
}
</script>
</body>
</html>