我有以下内容将JSON发布到C#Web API:
submitForm(data: any): Observable<Response> {
return this.http.post(
'https://localhost:44396/api/PostNewComputer/AddItem/?=', data,
{ headers: new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' }) }).subscribe(data => { return "test"; });
}
API控制器:
public class PostNewComputerController : ApiController
{
[HttpPost]
public IHttpActionResult AddItem(HttpRequestMessage request)
{
//var dynamicObject = Json.Decode(jsonString);
var jsonString = request.GetQueryNameValuePairs();
string message;
using (SqlConnection con = new SqlConnection("data source = MYSERVER; initial catalog = AssetDB; integrated security = SSPI; persist security info = True; Trusted_Connection = Yes"))
{
using (SqlCommand cmd = new SqlCommand("POST_NEW_COMPUTER", con) { CommandType = CommandType.StoredProcedure })
{
try
{
cmd.Parameters.Add(new SqlParameter("@JSON_TEXT", SqlDbType.NVarChar)).Value = jsonString;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
message = "Item Successfully Added";
}
catch (Exception e)
{
//throw e;
message = e.Message;
}
}
return Ok(message);
}
}
}
我正在尝试从POST调用创建一个响应消息,然后当用户提交表单以显示帖子已经工作时,该消息被反馈到网页。
然而,这个当前的设置不起作用,我正在努力解决这个问题。
有正确的方法可以做到这一点吗?
答案 0 :(得分:0)
使用HttpResponseMessage
将讯息回发为:
[HttpPost]
[ResponseType(typeof(string))]
public HttpResponseMessage AddItem(HttpRequestMessage request)
{
HttpResponseMessage response = null;
string message = string.Empty;
try
{
.....
message = "Item Successfully Added";
}
catch (Exception e)
{
.....
message = e.Message;
}
response = Request.CreateResponse<string>(HttpStatusCode.OK, message);
return response;
}
答案 1 :(得分:0)
问题出在你的Angular服务中。您的API是正确的
在将映射回映射到subscribe
之前,您尝试json()
来自API的响应,您需要执行以下操作,请参阅以下内容:
首先,这应该是您的组件中的内容:
submitForm(data: any): Observable<Response> {
//this url can't be correct?
let url:string = 'https://localhost:44396/api/PostNewComputer/AddItem/?=';
return this.http.post(url, data, this._headers())
.map((res:Response) => res.json());
}
//Created a method to do the headers for you
private _headers():RequestOptionsArgs {
let headers:Headers = new headers();
headers.append('Content-Type', 'application/json');
let options:RequestOptionsArgs = new RequestOptions();
options.headers = headers;
return options;
}
然后,您可以按如下方式从您的组件中调用您的服务:
public functionName():void {
this.service.submitForm(data)
.subscribe((res:any) => {
//this will contain your response
},
(error:any) => {
//this will contain your error
});
}
您需要确保您发布的模型与预期的模型匹配。关于您要发布的网址,这似乎不正确,是不是https://localhost:44396/api/PostNewComputer/AddItem/
?