我尝试使用基本的CRUD操作制作简单的UI。 GET方法正常工作但我无法使POST方法工作(但是,当我想通过fiddler测试POST方法时,它可以工作,数据在数据库中正确插入...)
我的应用分为多个层次。 API控制器位于一个层中,angularJS代码和视图位于第二层(Web层)。 Web层在端口50004上运行,API层在54927端口上运行。所以我在angular文件中写了这段代码:
var serviceBase = 'http://localhost:54927/';
onlineTesting.constant('ngAuthSettings', {
apiServiceBaseUri: serviceBase,
clientId: 'onlineTesting'
});
我在网上发现我必须启用cors并在我的webconfig文件中添加一些代码,您可以在下面看到。
这就是我的角度文件中的内容:
var _addCategory = function (category) {
$http.post(serviceBase + 'api/Categories', category).then(function (response) {
return response;
});
};
api控制器:
[RoutePrefix("api/Item")]
public class CategoriesController : ApiController
{
ICategoriesRepository _categoriesRepo;
ICategoriesServices _categoriesServices;
public CategoriesController()
{
_categoriesRepo = new CategoriesRepository();
_categoriesServices = new CategoriesServices();
}
public HttpResponseMessage Post(Categories category)
{
var result = _categoriesServices.AddCategory(category.CategoryType);
if (result == category.CategoryId)
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, category);
return response;
}
else
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
public IHttpActionResult Get()
{
var categories = _categoriesServices.GetCategories();
return Ok(categories);
}
public IHttpActionResult Get(int id)
{
var categories = _categoriesServices.GetCategoryById(id);
return Ok(categories);
}
public IHttpActionResult Delete(int categoryId)
{
var result = _categoriesServices.RemoveCategoryById(categoryId);
if (result)
return Ok();
else
return BadRequest("Item ID doesn't exist in database");
}
public IHttpActionResult Put(Categories category)
{
var result = _categoriesServices.UpdateCategory(category);
if (result)
return Ok();
else
return BadRequest("Category has not been updated, please check your category.");
}
}
我也在我的webconfig文件中添加了这个:
<httpProtocol>
<customHeaders>
<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
<add name="Access-Control-Allow-Methods" value="GET, POST, PUT, DELETE, OPTIONS" />
</customHeaders>
</httpProtocol>
这是我调用addCategory方法的html文件的一部分:
div id="registration-form">
<h3 class="crudheader">Add new category</h3>
<div class='fieldset'>
<form action="#" method="post" data-validate="parsley">
<div class='row'>
<input type="text" maxlength="1000" data-required="true" placeholder="Enter new category"
data-error-message="Category is required" data-ng-model="category.categoryType">
<h5 data-ng-model="message">Place your text here ({{ message }})</h5>
</div>
<button type="button" data-ng-click="addCategory(category)">Submitt</button>
</form>
</div>
当我点击提交按钮时,我总是在Inspect元素的控制台选项卡中获取这些消息: 远程地址:127.0.0.1:8888
常规
请求网址:myURL(包含端口54927)
请求方法:选项
状态代码:405方法不允许
响应标题
HTTP / 1.1 405方法不允许
缓存控制:无缓存
Pragma:no-cache
允许:POST,GET,PUT
Content-Type:application / json;字符集= UTF-8
过期:-1
服务器:Microsoft-IIS / 8.0
X-AspNet-Version:4.0.30319
X-SourceFiles: =?UTF-8 2 B 4 QzpcVXNlcnNcQVBJIExhYlxEZXNrdG9wXE9ubGluZVRlc3RpbmdcTmV3T25saW5lVGVzdGluZ1xBcGlMYWIuT25saW5lVGVzdGluZy5BcGlMYXllclxhcGlcQ2F0ZWdvcmllcw ==?=
X-Powered-By:ASP.NET
Access-Control-Allow-Origin:*
Access-Control-Allow-Headers:Origin,X-Requested-With,Content-Type, 接受
Access-Control-Allow-Methods:GET,POST,PUT,DELETE,OPTIONS
日期:2015年3月19日星期四15:08:24 GMT
内容长度:76
请求标题
选项http://localhost:54927/api/Categories HTTP / 1.1
主持人:localhost:54927
代理连接:keep-alive
访问控制请求方法:POST
原产地:myURL(使用网址50004)
User-Agent:Mozilla / 5.0(Windows NT 6.3; WOW64)AppleWebKit / 537.36 (KHTML,像Gecko一样)Chrome / 41.0.2272.89 Safari / 537.36
Access-Control-Request-Headers:accept,content-type
接受: /
Referer:myUrl(端口50004)
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-GB,en-US; q = 0.8,en; q = 0.6
答案 0 :(得分:0)
我认为您需要对JSON.stringfy()
进行category
stringify
var _addCategory = function (category) {
$http.post(serviceBase + 'api/Categories', JSON.stringfy(category)).then(function (response) {
return response;
});
};
对象并传递给控制器操作&amp;删除动作&amp;表单中的方法属性。
<强>代码强>
ng-submit
在HTML上使用表单元素级别的<form data-validate="parsley" data-ng-submit="addCategory(category)">
<div class='row'>
<input type="text" maxlength="1000" data-required="true" placeholder="Enter new category"
data-error-message="Category is required" data-ng-model="category.categoryType">
<h5 data-ng-model="message">Place your text here ({{ message }})</h5>
</div>
<button type="submit">Submit</button>
</form>
方法
<强> HTML 强>
public HttpResponseMessage Post([FromBody] Categories category) {
var result = _categoriesServices.AddCategory(category.CategoryType);
if (result == category.CategoryId) {
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, category);
return response;
} else
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
<强>更新强>
您还可以在动作参数
中添加[FromBody]<强> CODE 强>
{{1}}
希望这可以帮助你,谢谢。
答案 1 :(得分:0)
我找到了解决方案。我通过PM安装了CORS包。然后在API层的WebApiConfig文件中添加了config.EnableCors(),并从web.config文件中删除了customHeaders。
原因是我不应该同时在web.config和“config.EnableCors()”中同时拥有这些行,因为config.EnableCors()也允许标题和方法,如果两者都在代码,他们遇到某种冲突,我的POST将无法正常工作。
答案 2 :(得分:0)
添加到前面提到的安装CORS包的内容,请确保包含以下行, [EnableCors(来源:&#34; http://mywebclient.azurewebsites.net&#34;,标题:&#34; &#34;,方法:&#34; &#34;)] 在API控制器中。
[EnableCors(origins: "http://mywebclient.azurewebsites.net", headers: "*", methods: "*")]
public class TestController : ApiController
{
// Controller methods not shown...
}
http://www.asp.net/web-api/overview/security/enabling-cross-origin-requests-in-web-api