WebApi 跨域調用

1.WebAPI添加類庫引用


2.WebApiConfig添加

config.EnableCors(new EnableCorsAttribute("*", "*", "*"));

3.控制器示例 

namespace WebApiTest.Controllers
{
    [EnableCors("*", "*", "*")]
    public class UserModelsController : ApiController
    {
        // GET: api/UserModels
        public List<UserModels> Get()
        {
           return  new List<UserModels>() { new UserModels() {Id=1,Name="小紅",EmailAddress="[email protected]" } };
        }

        // GET: api/UserModels/5
        public string Get(int id)
        {
            return "value";
        }
        public string Post([FromBody]UserModels value)
        {
            return value.Name;
        }

        // PUT: api/UserModels/5
        public string Put(int id, [FromBody]UserModels value)
        {
            return "你好" + id + "," + value.Name;
        }

        // DELETE: api/UserModels/5
        public void Delete(int id)
        {
        }
    }
}

4.示例1:Ajax調用PUT

$.ajax({
                url: "http://localhost:30172/api/UserModels/12",
                data: { "Name": "SSSSSSS" },
                type: "Put",
                success: function (data) {
                    $('#content').html(data);
                    alert(data);
                }
            });


示例2:HTML頁面調用

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
    <script src="js/jquery-1.12.0.min.js"></script>
</head>
<body>
<form id="form1" action="http://localhost:30172/Api/UserModels" method="post">
<input name="Name" id="Name"/>
<input name="EmailAddress"/>
<button>提交</button>
</form>
</body>
</html>



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章