我正在尝试用基本的CRUD操作制作简单的UI。GET方法可以正常工作,但我无法使POST方法工作(但是,当我想通过fiddler测试POST方法时,它可以工作,数据可以正确插入数据库…)
我的应用程序分为多个层。API控制器位于一层,angularJS代码和视图位于第二层(web层)。Web层在50004端口上运行,API层在54927端口上运行
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>
这是html文件的一部分,我在其中调用addCategory方法:
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
常规
请求URL:myURL(带有端口54927)
请求方法:OPTIONS
状态代码:405方法不允许
响应标头
HTTP/1.1 405方法不允许
缓存控制:无缓存
Pragma:无缓存
允许:POST、GET、PUT
内容类型:application/json;charset=utf-8
过期时间:-1
服务器:Microsoft IIS/8.0
X-AspNet-版本:4.0.30319
X-SourceFiles:=?UTF-8?BQzpcVXNlcnNcQVBJIExhYlxEZXNrdG9wXE9ubGluZVRlc3RpbmdcTmV3T25saW5lVGVzdGluZ1xBcGlMYWIuT25saw5lVGV zdGluzy5BcGlMYXllclxhcGlcQ2F0ZWdvcmllcw==?=
X-Powered-By-ASP.NET
访问控制允许来源:*
访问控制允许标头:原始、X-Requested-Wise、内容类型、,接受
访问控制允许方法:GET、POST、PUT、DELETE、OPTIONS
日期:2015年3月19日星期四15:08:24 GMT
内容长度:76
请求标头
选项http://localhost:54927/api/CategoriesHTTP://1.1
主机:localhost:54927
代理连接:保持活动
访问控制请求方法:POST
来源:myURL(带url 50004)
用户代理:Mozilla/5.0(Windows NT 6.3;WOW64)AppleWebKit/537.36(KHTML,类似壁虎)Chrome/40.2272.89 Safari/537.36
访问控制请求头:接受,内容类型
接受:/
引用人:myUrl(带端口50004)
接受编码:gzip、deflate、sdch
接受语言:en-GB,en-US;q=0.8,en;q=0.6
我认为您需要为category
执行JSON.stringfy()
,这将stringify
作为对象并传递给控制器操作&删除操作&表单.中的方法属性
代码
var _addCategory = function (category) {
$http.post(serviceBase + 'api/Categories', JSON.stringfy(category)).then(function (response) {
return response;
});
};
关于HTML在表单元素级上使用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>
更新
您也可以在动作参数中添加[FromBody]
代码
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);
}
希望这能帮到你,谢谢。
我找到了解决方案。我通过PM安装了CORS包。然后在API层的WebApiConfig文件中添加了配置。EnableCors(),并从web.config文件中删除了customHeaders。
原因是我不应该在web.config和"config.EnableCors()"中同时包含这两行,因为config.Enable Cors。EnableCors()还允许标头和方法,如果两者都在代码中,它们就会发生某种冲突,那么我的POST就无法工作。
添加到前面提到的安装CORS包的内容中,确保包含以下行,[EnableCors(起源:"http://mywebclient.azurewebsites.net",头:"",方法:"")]在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